<body>
<div class="box"></div>
</body>
.box{
width:200px;
height:200px;
background:lightgoldenrodyellow url(./imgs/PC.png) no-repeat;
background-position:left;
/* background-position:right;
background-position:top;
background-position:bottom;
background-position:left top;
background-position:left bottom;
background-position:right top;
background-position:right bottom; */
}
- background-position:
left
|right
|top
|bottom
|left top
|left bottom
|right top
|right bottom
|百分比 百分比
其中,background-position:0% 0%
,
第一个百分比,代表了 背景图像的水平位置,0%
则意味着背景图像的左边界与容器左边界重合;
第二个百分比,代表了背景图像的垂直位置,0%
则意味着背景图像的上边界与容器上边界重合。
- background-position:
right 20px bottom 40px
意思是,背景图像的右边界距离容器右边界20px
,背景图像下边界距离容器下边界40px
。
background-position:right 20px bottom 40px
同
background-position:calc(100% - 20px) calc(100% - 40px)
.box{
width:200px;
height:200px;
background:lightgoldenrodyellow url(./imgs/PC.png) no-repeat;
/* background-position:right 20px bottom 40px; */
background-position:calc(100% - 20px) calc(100% - 40px);
}
- 定位背景图片
将背景图片定位到容器右下角,且与容器右下角有部分间隙,水平、垂直 间隙宽度都等于容器内边距。
/* 第一种方式 */
.box{
width:200px;
height:200px;
background:lightgoldenrodyellow url(./imgs/PC.png) no-repeat;
padding:10px;
background-position:right 10px bottom 10px;
}
但是,如果要改动padding,就意味着要改3处 。
所以,《css世界》给出了 维护性更好的一种方式,如下:
.box{
width:200px;
height:200px;
background:lightgoldenrodyellow url(./imgs/PC.png) no-repeat;
padding:10px;
background-origin:content-box;
background-position:right bottom;
}
background-origin决定了背景图像左上角的放置位置,其默认值是padding-content
,即 背景图像的左上角与padding-box的左上角重合。
现将 background-origin修改为content-box
,此时,背景图像的左上角总是与content-box重合并平铺开来,所以背景图像总会与padding-box有 padding宽的间隔。