2011-10-24 92 views
11

現代瀏覽器允許添加多個以逗號分隔的背景元素。例如,我可以定義2點的背景是這樣的:如何在CSS中添加另一個背景圖像到現有背景

background: url(image1.png) no-repeat left top, url(image2.png) no-repeat right bottom; 

它的作品完美的事情,和所有的,但往往還有一種情況,那麼我想有一個背景始終應用元素,以及另一才把我加第二類或一些變性劑。例如我想以下代碼:

<style> 
    .one { background: url(image1.png) no-repeat left top; } 
    .two { background: url(image2.png) no-repeat right bottom;} 
</style> 

<div class="one two"></div> 

...與施加兩個背景返回元件(以上代碼將只返回秒)。

在現代css中添加第二個沒有完全複製第一個的方法嗎?

回答

-1

我知道你不想完全複製任何東西,但我會做這樣的事情

.one{ 
    background: url(image1.png) no-repeat left top; 
    } 

.two{ 
    background: url(image1.png) no-repeat left top, 
    background: url(image2.png) no-repeat right bottom; 
} 

其中第二類基本「覆蓋」第一課。

另一種選擇是使用動態樣式表語言,如LESS(http://lesscss.org/),您可以在其中使用變量。

在更短的,你可以做這樣的事情

@twoBackgrounds: url(image1.png) no-repeat left top; 

.one{ 
    @twoBackgrounds; 
    } 

.two{ 
    @twoBackgrounds, 
    background: url(image2.png) no-repeat right bottom; 
} 
+0

謝謝你少想法。如果沒有本地解決方案,我可能會使用它,但我仍然希望有一個本地解決方案。 :) –

+0

你必須用逗號分開背景屬性,否則只使用最後一個聲明。重複第一個的想法是正確的,但使用LESS變量是保持乾燥的簡單方法。 – Ronald

2

@Jason

此代碼將無法正常工作。你必須使用這個

.one { 
    background: url(image1.png) no-repeat left top; 
} 

.two { 
    background: url(image1.png) no-repeat left top, url(image2.png) no-repeat right bottom; 
} 
2

你可以用一個僞元素來做到這一點,像之前或之後,並添加一個換行元素。

.wrap { 
 
    width:500px; 
 
    height: 500px; 
 
    border:1px solid red; 
 
    position:relative; 
 
} 
 
.one { 
 
    width:100%;height:100%; 
 
    background-image: url(http://dummyimage.com/250x250/dfdbb9/dfdbb9.png); 
 
    background-repeat:no-repeat; 
 
    background-position:left top; 
 
} 
 
.two:after {  
 
    content: ''; 
 
    position: absolute; 
 
    width: 100%; 
 
    height: 100%; 
 
    top:0; 
 
    left:0; 
 
    z-index: -1; 
 
    background-image: url(http://dummyimage.com/250x250/b9d9df/b9d9df.png); 
 
    background-repeat:no-repeat;   
 
    background-position:right bottom; 
 
}
<div class="wrap"> 
 
    <div class="one two"></div> 
 
</div>

這裏是的jsfiddle:http://jsfiddle.net/alexut/jz0pm47t/1/