文章目录
CSS 背景
CSS 背景属性用于为元素添加背景效果。包括以下 CSS 背景属性:
- background-color
- background-image
- background-repeat
- background-attachment
- background-position
- background(简写属性)
CSS background-color
background-color 属性指定元素的背景颜色。
示例
页面的背景颜色设置如下:
body {
background-color: lightblue;
}
使用 CSS,颜色通常由以下方式指定:
有效的颜色名称 - 如“red”
HEX 值 - 如“#ff0000”
RGB 值 - 如“rgb(255,0,0)”
其他元素
您可以为任何 HTML 元素设置背景颜色:
示例
此处,<h1>
、<p>
和 <div>
元素将具有不同的背景颜色:
h1 {
background-color: green;
}
div {
background-color: lightblue;
}
p {
background-color: yellow;
}
不透明度/透明度
不透明度属性指定元素的不透明度/透明度。它可以取 0.0 - 1.0 之间的值。值越低,透明度越高:
示例
div {
background-color: green;
opacity: 0.3;
}
注意:使用不透明度属性为元素的背景添加透明度时,其所有子元素都会继承相同的透明度。这会使完全透明元素内的文本难以阅读。
使用 RGBA 实现透明度
如果您不想将不透明度应用于子元素(如上例所示),请使用 RGBA 颜色值。以下示例设置背景颜色的不透明度,而不是文本的不透明度:
CSS 颜色可以使用 RGB 作为颜色值。除了 RGB,您还可以使用带有 alpha 通道 (RGBA) 的 RGB 颜色值 - 它指定颜色的不透明度。
RGBA 颜色值指定为:rgba(红色、绿色、蓝色、alpha)。alpha 参数是介于 0.0(完全透明)和 1.0(完全不透明)之间的数字。
示例
div {
background: rgba(0, 128, 0, 0.3) /* 不透明度为 30% 的绿色背景 */
}
CSS background-image
background-image 属性指定用作元素背景的图像。
默认情况下,图像会重复,因此会覆盖整个元素。
示例
设置页面的背景图像:
body {
background-image: url("paper.gif");
}
示例
此示例显示了文本和背景图像的不良组合。文本几乎不可读:
body {
background-image: url("bgdesert.jpg");
}
注意:使用背景图像时,请使用不会干扰文本的图像。
还可以为特定元素设置背景图像,例如 <p>
元素:
示例
p {
background-image: url("paper.gif");
}
CSS background-repeat
默认情况下,background-image 属性会水平和垂直重复图像。
某些图像应仅水平或垂直重复,否则它们会看起来很奇怪,如下所示:
示例
body {
background-image: url("gradient_bg.png");
}
如果上面的图像仅水平重复(background-repeat: repeat-x;),背景会看起来更好:
示例
body {
background-image: url("gradient_bg.png");
background-repeat: repeat-x;
}
提示:要垂直重复图像,请设置 background-repeat: repeat-y;
CSS background-repeat: no-repeat
仅显示一次背景图像也是由 background-repeat 属性指定的:
示例
仅显示一次背景图像:
body {
background-image: url("img_tree.png");
background-repeat: no-repeat;
}
在上面的例子中,背景图像与文本放在了同一个位置。我们想改变图像的位置,这样它就不会过多地干扰文本。
CSS background-position
background-position 属性用于指定背景图像的位置。
示例
将背景图像定位在右上角:
body {
background-image: url("img_tree.png");
background-repeat: no-repeat;
background-position: right top;
}
CSS Background Attachment
background-attachment 属性指定背景图像是否应滚动或固定(不会随页面的其余部分滚动):
示例
指定背景图像应固定:
body {
background-image: url("img_tree.png");
background-repeat: no-repeat;
background-position: right top;
background-attachment: fixed;
}
示例
指定背景图像应随页面的其余部分滚动:
body {
background-image: url("img_tree.png");
background-repeat: no-repeat;
background-position: right top;
background-attachment: scroll;
}
CSS 背景简写属性
为了缩短代码,也可以在一个属性中指定所有背景属性。这称为简写属性。
不必这样写:
body {
background-color: #ffffff;
background-image: url("img_tree.png");
background-repeat: no-repeat;
background-position: right top;
}
您可以使用简写属性 background:
示例
使用简写属性在一个声明中设置背景属性:
body {
background: #ffffff url("img_tree.png") no-repeat right top;
}
使用简写属性时,属性值的顺序为:
- background-color
- background-image
- background-repeat
- background-attachment
- background-position
如果缺少其中一个属性值,只要其他属性值按此顺序排列,也没关系。请注意,我们在上面的示例中没有使用 background-attachment 属性,因为它没有值。
总结
本文介绍了的CSS背景属性使用,如有问题欢迎私信和评论