针对容器某个角对背景图片做偏移定位
现在就假设想针对容器右下角右侧20px偏移,底部10px偏移有如下几种方式1、原理设置透明边框div { background: url(../images/code-pirate.svg) no-repeat 100% 100% #58a; border-right: 20px solid transparent; border-bottom: 10px solid transparent; }
2、给background-position指定right bottom值
备注:因为css3中background-position 属性已经得到扩展, 它允许我们指定背景图片距离任意角的偏移量, 只要我们在偏移量前面指定关键字div { background: url(../images/code-pirate.svg) no-repeat #58a; background-position: right 20px bottom 10px; /*上面一句写成这样也是同样的效果 background-position: bottom 10px right 20px ;*/ }
3、针对第二种方式实现的回退方案
div { background: url(../images/code-pirate.svg) no-repeat bottom right #58a; background-position: right 20px bottom 10px; }
具体效果见
4、使用padding加background-origin备注:此方案适用于偏移量与容器的内边距一致,默认情况下background-position 是以 padding box 为准的,所以background-position:top left; top left是以 padding box 的左上角,之所以默认值是padding-box这样边框才不会遮挡背景图片div { padding: 10px 20px; background: url(../images/code-pirate.svg) no-repeat #58a bottom right; /* 或 100% 100% */ background-origin: content-box; }
具体效果见
5、使用透明边框加background-origindiv { 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; }
6、使用calc计算宽高
div { background: url(../images/code-pirate.svg) no-repeat #58a; background-position: calc(100% - 20px) calc(100% - 10px); }
具体效果见
备注:以前只知道calc中的运算符需要两侧各加一个空白符,否则会产生解析错误,现在知道真正的原因是为了向前兼容,在未来,在 calc() 内部可能会允许使用关键字,而这些关键字可能会含连字符(即减号)