CSS background 属性用于定义元素的背景效果。有 5 个 CSS 背景属性会影响 HTML 元素:
背景颜色
背景图片
背景重复
背景附件
背景位置
background-color 属性用于指定元素的背景颜色。
您可以像这样设置背景颜色:
<!DOCTYPE html> <html> <head> <style> h2,p{ background-color: #b0d4de; } </style> </head> <body> <h2>My first CSS page.</h2> <p>Hello RocSchool. This is an example of CSS background-color.</p> </body> </html>
输出:
你好Javatpoint。这是 CSS 背景色的示例。
background-image 属性用于将图像设置为元素的背景。默认情况下,图像覆盖整个元素。您可以为这样的页面设置背景图像。
<!DOCTYPE html> <html> <head> <style> body { background-image: url("paper1.gif"); margin-left:100px; } </style> </head> <body> <h1>Hello RocSchool.com</h1> </body> </html>
注意:背景图片应根据文字颜色选择。文本和背景图像的不良组合可能是导致网页设计不佳且不可读的原因。
默认情况下, background-image 属性在水平和垂直方向上重复背景图像。某些图像仅在水平或垂直方向重复。
如果图像仅水平重复,背景看起来会更好。
背景重复:重复-x;
背景重复:重复-y;
<!DOCTYPE html> <html> <head> <style> body { background-image: url("gradient_bg.png"); background-repeat: repeat-x; } </style> </head> <body> <h1>Hello RocSchool.com</h1> </body> </html>
4) CSS 背景附件
background-attachment 属性用于指定背景图像是固定的还是随浏览器窗口中页面的其余部分滚动。如果您设置固定背景图像,则在浏览器中滚动期间图像将不会移动。让我们以固定背景图像为例。
background: white url('bbb.gif'); background-repeat: no-repeat; background-attachment: fixed;
background-position 属性用于定义背景图像的初始位置。默认情况下,背景图片位于网页的左上角。
您可以设置以下位置:
center
top
bottom
left
right
background: white url('good-morning.jpg'); background-repeat: no-repeat; background-attachment: fixed; background-position: center;