背景
- 通过CSS背景属性,可以给页面元素添加背景样式。
- 背景属性可以设置 背景颜色、 背景图片、背景平铺、背景图片位置、背景图像固定等。
3.1 背景颜色
background-color
一般情况下元素背景颜色默认值是transparent(透明的)。
3.2 背景图片
background-image
常见于logo或者一些装饰性小图片或者是超大的背景图片。
优点是非常便于控制位置。
background-image:none/url
<style>
div {
width: 500px;
height: 500px;
background-image: url(https://hbimg.huabanimg.com/c09959ccd0e4a7c3cd35cd4dac3d9640bdd3ae31155e2-VsJIXr_fw658/format/webp);
}
</style>
<body>
<div>
</div>
</body>
3.3背景平铺
**backgroun-repeat **
平铺/ 不平铺/ 沿着x轴平铺/ 沿着y轴平铺
<style>
div {
width: 500px;
height: 500px;
background-image: url(https://hbimg.huabanimg.com/c09959ccd0e4a7c3cd35cd4dac3d9640bdd3ae31155e2-VsJIXr_fw658/format/webp);
background-repeat: no-repeat;
}
</style>
<body>
<div>
</div>
3.4 背景图片位置
background-position 1改变图片在背景中的位置
background-position: top;
background-position: bottom;
background-position: left;
background-position: right;
background-position: 50px center;
/* x轴 y轴 */
3.5背景图像固定(背景附着)
background-attachment
设置背景图像是否固定或者随着页面的其余部分滚动。
后期可以做视差滚动效果
<style>
body {
background-image: url(night.jpg);
background-repeat: no-repeat;
background-position: center top;
background-attachment: fixed;
/* 把背景图片固定 */
color: #fff;
font-size: 20px;
}
</style>
</head>
<body>
<p>1111111111111111111</p>
<p>1111111111111111111</p>
<p>1111111111111111111</p>
<p>1111111111111111111</p>
<p>1111111111111111111</p>
<p>1111111111111111111</p>
<p>1111111111111111111</p>
<p>1111111111111111111</p>
<p>1111111111111111111</p>
<p>1111111111111111111</p>
<p>1111111111111111111</p>
<p>1111111111111111111</p>
<p>1111111111111111111</p>
<p>1111111111111111111</p>
<p>1111111111111111111</p>
<p>1111111111111111111</p>
<p>1111111111111111111</p>
<p>1111111111111111111</p>
<p>1111111111111111111</p>
<p>1111111111111111111</p>
<p>1111111111111111111</p>
<p>1111111111111111111</p>
<p>1111111111111111111</p>
<p>1111111111111111111</p>
<p>1111111111111111111</p>
<p>1111111111111111111</p>
<p>1111111111111111111</p>
<p>1111111111111111111</p>
<p>1111111111111111111</p>
<p>1111111111111111111</p>
<p>1111111111111111111</p>
<p>1111111111111111111</p>
</body>
3.6背景复合写法
为了简化背景属性的代码,我们可以将这些属性合并简写在同一个属性 background中,从而节约代码量。
/* 背景颜色 背景图片地址 背景平铺 背景图像滚动 背景图像位置 */
background: black url(night.jpg) no-repeat fixed center top;
3.7背景色半透明
<style>
div {
width: 300px;
height: 300px;
background: rgba(0, 0, 0, 0.1);
}
</style>
</head>
<body>
<div></div>
</body>