CSS背景
css可以对背景颜色和背景图片进行设置。
背景颜色
background-color
属性是对背景颜色进行设置。与color
属性完全相同。
background-color: pink;```
#### 背景图片
`background-image`属性是对背景图片进行设置,通过`url`设置图片路径。
```css
background-image: url("../img/鼬.jpg");
背景平铺
background-repeat
属性是对背景图片平铺效果进行设置,
默认值为repeat
,no-repeat
取消平铺效果,repeat-x
水平方向平铺,repeat-y
垂直方向平铺。
background-repeat: no-repeat ;
背景定位
background-postion
属性设置图片的位置。其中有两个值,一个为x轴方向,另一个为y轴方向(垂直向下)设值方式如下:
- 方位名词,如top、left、right、bottom;
- 精确定位,如10px,20px;
- 混搭,如10px center。
background-position: left center;
background-position: 300px 30px;
background-position: center 10px;
注意: 采用方位名词设值,只写一个值,另一个默认为center
。
背景附着(滚动)
background-attachment
背景附着,默认为scroll
滚动的,图片随着文字在滚动;fixed
背景固定文字在滚动,背景图片不变。
background-attachment: fixed;
背景简写
background
: 背景颜色 背景图片地址 背景位置 背景平铺 背景附着(可省略)。
background: #fff url() 0 0 no-repeat;
background: #fff url("../img/鼬.jpg") 20px center no-repeat fixed;
背景透明(css3)
a
为透明度,0~1,值越低透明效果越强。
background: rgba(0,0,0,0.3);
背景缩放(css3)
background-size
属性设置图片的缩放效果,有宽
和高
两个属性值,
一般情况下为了保持图片原有比例,只设置一个值。
background-size: 50%;
background-size: 50px;
cover
会自动调整缩放比例,保证图片始终填充背景区域,溢出的部分会被隐藏。
background-size: cover;
contain
图片保持原有比例,不断放大,当某一边与背景区域重合,就不在放大。
background-size: contain;
多背景(css3)
- 每组属性之间用
逗号
隔开; - 如果设置的多重背景图片存在重叠的部分,前者覆盖后者;
- 为了避免背景色将图片遮住,背景色通常设置再最后一组。
body {
background: url("../img/鼬.jpg") left top no-repeat,
url("../img/魔兽.jpeg") left bottom no-repeat,
url("../img/王者荣耀.jpg") right center no-repeat #000000;
}
引入图片使用
background
还是img
?两者都能实现效果,使用原则长期固定不变的图片使用background
,经常变动的图片使用img
来引入。