灵活的背景定位

有时候,我们希望让背景图对容器的某个角做偏移,但是在之前的css中,我们只能指定距离左上角的偏移量,甚为头疼,今天我们就来讲几种方法来灵活的定位背景

background-position的扩展语法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
	<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<style type="text/css" media="screen">
html{
height:100%;
}

body{
display:flex;
height:100%;
margin:0;
}

div{
margin:auto;
width:300px;
height:300px;
background:#fc4766 url(imgs/6.jpg) no-repeat;
background-position:right 20px top 30px;
}

</style>

</head>
<body>
<div class="outer">
哈哈哈哈哈
</div>
</body>
</html>

效果如下:
;

现在我们有了background-position之后,,就可以让背景定位与任何一个角,通过left,right,top,bottom,center,以及相对应的具体数值或百分数,来灵活定位

background-origin

还有一种常见的场景,偏移量与容器内边距一致,这时候我么的css代可能是酱紫的:

1
2
3
4
5
6
7
div{
margin:auto;
width:300px;
height:300px;
background:#fc4766 url(imgs/6.jpg) no-repeat;
background-position:right 20px top 30px;
}

这样子写效果是达到了,可是下次如果padding改变了,,我们不是又要手动修改了吗?T_T
还好,我们有个属性能让我们欢快会background-origin
前一篇曾今说过,background-origin是以padding-box为准的,所以background-position也是以padding-box为准,好,现在我们来使用它,使他以content-box为值,这样就背景的偏移量就是内边距了 ,来达到上面那个效果:

1
2
3
4
5
6
7
8
div{
margin:auto;
width:300px;
height:300px;
padding:50px;
background:#fc4766 url(imgs/6.jpg) no-repeat right top;
background-origin:content-box;
}

ok 完美

calc()

如果我们继续使用旧的background-posiotn语法,相对于左上角来定位,我们要怎么弄呢?
也就是说距离左边有个 100% - 20px 的水平偏移,距离顶部有个 100% - 30px 的垂直偏移。好在我们有个calc()css函数可以帮我们做到:

1
2
3
4
5
6
7
div{
margin:auto;
width:300px;
height:300px;
background:#fc4766 url(imgs/6.jpg) no-repeat;
background-position:calc(100% - 20px) calc(100% - 30px);
}

背景里的百分比是在元素大小减去背景大小后的值为100%

很强势,实际上,calc()在现在应用广泛,不仅仅体现在上面的背景定位上,还可以使用在任何你想确定一个值得地方,不过要注意的是,calc()括号里的运算符的左右两边必须要有空格,不然它是无效的,勿忘哈

文章目录
  1. 1. background-position的扩展语法
  2. 2. background-origin
  3. 3. calc()