2015-12-14 61 views
2

我有一個線性漸變:2em red, 4em yellow如何移動背景漸變獨立於容器寬度

.bar { 
    background: repeating-linear-gradient(90deg, red 0, red 2em, yellow 2em, yellow 6em); 
    background-position-x: 0em; 
} 

如果我通過background-position-x: 1em;

我希望我的梯度將開始移動漸變一個1em向右與1em yellow塊和2em red塊。

取而代之,它抓住了紅色的div末尾的前一個塊。所以我得到了3em red, 4em yellow,這違反了我的規則。

這裏是一個演示: http://codepen.io/anon/pen/XXmOPB?editors=110

回答

3

重複梯度具有循環重複,因此沒有明確的background-size設置添加你必須把它當作雖然的31em磚放在一個挨着另一個。所以當背景在X軸上的位置設置爲1em時,它變得像-30em1em是一塊瓷磚,1em32em將是另一塊瓷磚等等。這就是爲什麼你看到容器內第一個瓦片(紅色)和第二個瓦片(其中有6em * 5)作爲背景圖像的最後一個1em

在我提供的答案here的回答中討論了將背景漸變圖像的尺寸作爲31em的原因。


的解決問題的方法是顯式設置在X軸的background-size爲等於實際梯度大小。

.foo div.bar { 
 
    width: 31em; 
 
    height: 2em; 
 
} 
 
.foo2 div.bar { 
 
    width: 33em; 
 
    height: 2em; 
 
} 
 
.bar { 
 
    background: repeating-linear-gradient(90deg, red 0, red 2em, yellow 2em, yellow 6em); 
 
    background-size: 6em 100%; 
 
    background-position-x: 1em; 
 
} 
 

 
/* Just for demo */ 
 
div { 
 
    margin: 10px; 
 
}
<div class="foo"> 
 
    <div class="bar"> 
 
    </div> 
 
</div> 
 
<div class="foo2"> 
 
    <div class="bar"> 
 
    </div> 
 
</div>


而且,請注意background-position-xbackground-position-y最初提出了CSS3(並得到拒絕)。它是now approved for Level 4,但爲了支持舊版瀏覽器,最好使用下面給出的速記屬性。我剛剛證實,一些較舊的Firefox版本不支持background-position-x

background-position: 1em 0em;