灵活的背景定位

2017-07-24  本文已影响0人  _菡曳_

background-position的扩展语法方案
background-position属性允许我们制定背景图片距离任意角的偏移量,只要我们在偏移量前面指定关键字。

.mybox{
    height: 200px;
    background: url(1.png) no-repeat #58a;
    background-position: right 20px bottom 10px;
}
偏移效果

还需要一个合适的回退方案使其适应不支持此语法的浏览器:

.mybox{
    height: 200px;
    background: url(1.png) 
    no-repeat bottom right #58a;
    background-position: right 20px bottom 10px;
}

background-origin方案
一种常见的情况:偏移量与容器的内边距一致
若采用上述方案,代码如下:

.mybox{
    padding: 10px;
    height: 200px;
    background: url(1.png) 
    no-repeat bottom right #58a;
    background-position: right 10px bottom 10px;
}

但是如果我们要修改内边距的话,就需要改动三个地方!幸亏还有一个更简单的方法可以实现这个需求:让它自动跟着设定的内边距走,不用另外声明偏移量的值。

默认情况下,background-position是以padding box为准的,这样边框才不会遮住背景图片,因此top left默认指的是padding box的左上角。但是使用background-origin可以改变这种行为,如果把它的值改成content-box,此时背景图片的偏移量会以内容的边缘作为基准。

.mybox{
    padding: 10px;
    height: 200px;
    background: url(1.png) no-repeat bottom right #58a;
    background-origin: content-box;
}

calc()方案
calc()函数允许我们执行偏移计算,可以完美在background-position属性中使用:

.mybox{
    padding: 10px;
    height: 200px;
    background: url("1.png") no-repeat bottom right #58a;
    background-position: calc(100% - 20px) calc(100% - 10px);
}

注:在calc()函数内部的-、+运算符两侧要添加一个空白符,否则会产生解析错误!

上一篇 下一篇

猜你喜欢

热点阅读