一、背景图片
1.背景图片位置
background-position属性设置背景图像的起始位置
1.背景位置-固定值 第一个值表示水平位置(值增大往右移,值可以为负)第二个值表示垂直位置(值增大往下移,值可以为负)
2.背景位置-百分比 第一个值表示水平位置(值增大往右移,值可以为负)第二个值表示垂直位置(值增大往下移,值可以为负)
水平移动距离:(盒子宽度-图像宽度)*百分比
垂直移动距离:(盒子高度-图像高度)*百分比
3.背景位置-关键词 水平取值:left center right
垂直取值:top center bottom
这种方式的设置可以交换水平和垂直位置,如果省略一个值,另一个值默认center
.bgc-img {
width: 500px;
height: 500px;
background-color: red;
background-image: url("./QQ截图20221207105017.png");
background-repeat: no-repeat;
background-position: -10 34;
background-position: 10% 20%;
background-position: center 20%;
background-position: right 122px;
background-position: 222px center;
}
2.背景图片附着
background-attachment设置背景图像是否固定或者随着页面的其余部分滚动。
值 | 说明 |
---|---|
scroll | 背景图片随页面的其余部分滚动。默认 |
fixed | 背景图像是固定的 |
<div class="bgc-attach"></div>
<div class="img2"></div>
<div class="img3"></div>
<style>
*{
margin: 0;
}
.bgc-attach{
width: 100%;
height: 970px;
background-color: deepskyblue;
background-image: url("https://c-ssl.duitang.com/uploads/item/201807/23/2018072394037_Z2mVP.jpeg");
background-size: cover;
background-repeat: no-repeat;
/* 固定 相对于盒子固定 */
background-attachment: fixed;
/* 固定 相对于浏览器固定 */
/* background-attachment: fixed; */
}
.img2{
width: 100%;
height: 970px;
background-image: url("https://c-ssl.duitang.com/uploads/item/201807/23/2018072393713_xLFQs.jpeg");
background-attachment: fixed;
background-repeat: no-repeat;
background-size: cover;
}
.img3{
width: 100%;
height: 970px;
background-image: url("https://c-ssl.duitang.com/uploads/item/201807/23/2018072393713_4rWKN.jpeg");
background-attachment: fixed;
background-size: cover;
background-repeat: no-repeat;
}
</style>
3.背景缩放
通过background-size设置背景图片的尺寸。其参数设置如下:
1.可以设置长度单位(px)或百分比(设置百分比时,参照盒子的宽高)。
2.设置为cover时,会自动调整缩放比例,保证图片始终填充满背景区域,如有溢出部分则会被隐藏。
3.设置为contain时,会自动调整缩放比例,保证图片始终完整显示在背景区域。
插入图片和背景图片的区别:
-
插入图片在更改图片大小时使用属性 width 和 height ,更改图片位置使用 margin 或 padding 盒模型。
-
背景图片在更改图片大小时使用 background-size 属性,更改图片位置时使用background-position属性。
-
一般情况下背景图片适合做一些小图标使用,产品展示之类的就用插入图片
4.多背景
以逗号分隔可以设置多背景,可用于自适应布局。
不同的背景图像用逗号隔开,并且图像会彼此堆叠,其中的第一幅图像最靠近观看者。
<style>
div{
width: 700px;
height: 500px;
background-image: url("./QQ截图20