CSS揭秘之《灵活的背景定位》

针对容器某个角对背景图片作偏移定位
如今就假设想针对容器右下角右侧20px偏移,底部10px偏移
有以下几种方式
一、原理设置透明边框css

div {
            background: url(../images/code-pirate.svg) no-repeat 100% 100% #58a;
            border-right: 20px solid transparent;
            border-bottom: 10px solid transparent;
        }

二、给background-position指定right bottom值
备注:由于css3中background-position 属性已经获得扩展, 它容许咱们指定背景图片距离任
意角的偏移量, 只要咱们在偏移量前面指定关键字css3

div {
            background: url(../images/code-pirate.svg) no-repeat #58a;
            background-position: right 20px bottom 10px;
            /*上面一句写成这样也是一样的效果
            background-position: bottom 10px right 20px ;*/
        }

三、针对第二种方式实现的回退方案svg

div {
            background: url(../images/code-pirate.svg) no-repeat bottom right #58a;
            background-position: right 20px bottom 10px;
        }

具体效果见 连接
四、使用padding加background-origin
备注:此方案适用于偏移量与容器的内边距一致,默认状况下background-position 是以 padding box 为准的,因此background-position:top left; top left是以 padding box 的左上角,之因此默认值是padding-box这样边框才不会遮挡背景图片url

div {
            padding: 10px 20px;
            background: url(../images/code-pirate.svg) no-repeat #58a bottom right;
            /* 或 100% 100% */
            background-origin: content-box;
        }

具体效果见连接
五、使用透明边框加background-originspa

div {
            padding: 0;
            border-right: 20px solid transparent;
            border-bottom: 10px solid transparent;
            background: url(../images/code-pirate.svg) no-repeat #58a bottom right;
            /* 或 100% 100% */
            background-origin: padding-box;
        }

六、使用calc计算宽高code

div {
            background: url(../images/code-pirate.svg) no-repeat #58a;
            background-position: calc(100% - 20px) calc(100% - 10px);
        }

具体效果见连接图片

备注:之前只知道calc中的运算符须要两侧各加一个空白符,不然会产生解析错误,如今知道真正的缘由是为了向前兼容,在将来,在 calc() 内部可能会容许使用关键字,而这些关键字可能会含连字符(即减号)get

相关文章
相关标签/搜索