css3 background-clip background-origin屬性詳解

好久沒寫樣式,前2天有個新來的同事問我background-clip這個css3 的屬性,我當時只記這個是裁剪,具體怎麼裁剪已經忘記了,找了下資料整理下方便以後記憶,它有三個屬性:

1.border-box

一.background-clip

這個看上去有點像box-sizing的屬性,其實不是,border-box是默認值,大概意思是背景延伸到border的外邊緣。看下面代碼

    <style>
    .test{
        width: 300px;
        height: 300px;
        border: 10px dotted #aaa;
        background-color: yellow;
        margin:100px auto;
        padding: 20px;
        background-clip:border-box;    
    }  
    </style>
</head>
<body>
    <div class="test">
    </div>
</body>

效果如下(背景延伸到border的外邊緣):
在這裏插入圖片描述

二.background-origin

<style>
    .test {
        width: 300px;
        height: 300px;
        padding: 20px;
        border: 10px dotted #aaa;
        margin: 100px auto;
        background-repeat:no-repeat;
        background-image: url('1.png');
        background-origin: padding-box;
        background-size: cover;
    }
</style>
</head>

<body>
    <div class="test">
    </div>
</body>

背景圖是以border爲起點
在這裏插入圖片描述
效果是一樣的,都是在border外邊緣顯示

2.content-box
一.background-clip

box-sizing也有這個屬性,背景剪切到內容區域,上面代碼內容區域是300X300,所以300之外的區域都被剪切了。
效果如下:
在這裏插入圖片描述

二.background-origin
<style>
    .test {
        width: 300px;
        height: 300px;
        padding: 20px;
        border: 10px dotted #aaa;
        margin: 100px auto;
        background-repeat:no-repeat;
        background-image: url('1.png');
        background-origin: padding-box;
        background-size: cover;
    }
</style>
</head>

<body>
    <div class="test">
    </div>
</body>

背景是以content內容爲起點
在這裏插入圖片描述

3.padding-box

一.background-clip

顧名思義就是在還包括padding區域,不包括border,所以是content-box+padding。
效果如下:
在這裏插入圖片描述

二.background-origin

背景圖以padding爲起點,不包括border

<style>
    .test {
        width: 300px;
        height: 300px;
        padding: 20px;
        border: 10px dotted #aaa;
        margin: 100px auto;
        background-repeat:no-repeat;
        background-image: url('1.png');
        background-origin: padding-box;
        background-size: cover;
    }
</style>
</head>

<body>
    <div class="test">
    </div>
</body>

</body>

在這裏插入圖片描述

這個兩個屬性是css3的屬性,瀏覽器兼容範圍 chrome15+、IE9+、Edge12+、Firefox4+、Opera11.5+、Safari7+。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章