【CSS学习笔记5】-背景
2023-09-21 本文已影响0人
兔小小
背景颜色 background-color
body {
background-color: lightblue;
}
h1 {
background-color: green;
}
div {
background-color: lightblue;
}
p {
background-color: yellow;
}
其他表示颜色的值
- 有效的颜色名称 - 如“red”
- 十六进制值 - 如“#ff0000”
- 一个 RGB 值 - 如“rgb(255,0,0)”
![](https://img.haomeiwen.com/i21922576/a4e99b9afd415a21.png)
不透明度
div {
background-color: green;
opacity: 0.3;
}
![](https://img.haomeiwen.com/i21922576/6fb8e9f256a221c3.png)
RGBA
div {
background: rgba(0, 128, 0, 0.3) /* Green background with 30% opacity */
}
![](https://img.haomeiwen.com/i21922576/133e8c1ab8de3894.png)
背景图片 background-image
body {
background-image: url("paper.gif");
}
![](https://img.haomeiwen.com/i21922576/8702e5da7e728284.png)
body {
background-image: url("bgdesert.jpg");
}
![](https://img.haomeiwen.com/i21922576/6b6efb89fa530646.png)
特定元素的背景图片:
p {
background-image: url("paper.gif");
}
![](https://img.haomeiwen.com/i21922576/16dbdef59e51ffb7.png)
背景重复 background-repeat
默认情况下,该属性在水平和垂直方向上重复图像。
body {
background-image: url("gradient_bg.png");
}
![](https://img.haomeiwen.com/i21922576/fa0912a21c3a8cb4.png)
如果上图仅水平重复(),背景将看起来更好background-repeat: repeat-x;
body {
background-image: url("gradient_bg.png");
background-repeat: repeat-x;
}
![](https://img.haomeiwen.com/i21922576/41001a2d5dc6d562.png)
没有重复:background-repeat: no-repeat;
body {
background-image: url("img_tree.png");
background-repeat: no-repeat;
}
![](https://img.haomeiwen.com/i21922576/6c34fa1dbe900224.png)
背景位置 background-position
body {
background-image: url("img_tree.png");
background-repeat: no-repeat;
background-position: right top;
}
![](https://img.haomeiwen.com/i21922576/e0d697eb78480b51.png)
绑定 attachment
滚动图片不动:
body {
background-image: url("img_tree.png");
background-repeat: no-repeat;
background-position: right top;
background-attachment: fixed;
}
![](https://img.haomeiwen.com/i21922576/2caba2cc3887d9d2.png)
![](https://img.haomeiwen.com/i21922576/5473cf784fe77930.png)
指定背景图像应与页面的其余部分一起滚动:
body {
background-image: url("img_tree.png");
background-repeat: no-repeat;
background-position: right top;
background-attachment: scroll;
}
![](https://img.haomeiwen.com/i21922576/ba73132cec78f03a.png)
缩短代码 background
这个代码还是比较长的
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
![](https://img.haomeiwen.com/i21922576/5d389ab2c92ee963.png)
缺少其中一个属性值并不重要,只要其他的按此顺序排列。请注意,在上面的示例中,我们不使用 background-attachment 属性,因为它没有值。