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

相關文章
相關標籤/搜索