2015-07-20 85 views
4

我有以下代碼爲了使背景圖像變暗。與背景圖像的DIV那麼內部的一個div與透明度有沒有更好的方法來使背景圖像變暗?

<div class="slide"> 
    <div class="slide-overlay"> 
    <div class="slide-content"> 
     <h1>Blah blah content</h1> 
    </div> 
    </div> 
</div> 

而且我的造型像這樣

.slide 
    background-image: url('/assets/img/bg-cover.jpg') 
    background-size: cover 
.slide-overlay 
    background-color: rgba(0, 0, 0, .2) 

有誰知道一個更優雅的解決方案的背景色填充呢?

+0

你的代碼看起來不錯,我 –

+0

我也一樣,這是我會怎麼做。 –

+0

謝謝你們,我會堅持我的話。乾杯 –

回答

6

您可以簡化的唯一方法就是省略.slide-overlay容器,並添加僞元素(:before, :after)代替。

這裏將是此溶液:

.slide { 
 
    background-color: tomato; 
 
    background-size: cover; 
 
} 
 
.slide-content { 
 
    position: relative; 
 
    color: white; 
 
} 
 
.slide-content:nth-child(2):before, .slide-content:nth-child(3):before { 
 
    content: ""; 
 
    position: absolute; 
 
    left: 0; 
 
    right: 0; 
 
    top: 0; 
 
    bottom: 0; 
 
    background-color: rgba(0, 0, 0, 0.2); 
 
} 
 
.slide-content:nth-child(3) { 
 
    z-index: 1; 
 
} 
 
.slide-content:nth-child(3):before { 
 
    z-index: -1; 
 
}
<div class="slide"> 
 
    <div class="slide-content"> 
 
     <h1>No effects - just standard text.</h1> 
 
    </div> 
 
    <div class="slide-content"> 
 
     <h1>With overlay - text is below the overlay.</h1> 
 
    </div> 
 
    <div class="slide-content"> 
 
     <h1>With overlay - text is above the overlay.</h1> 
 
    </div> 
 
</div>

編輯:下面僞元件文本不再受分別覆蓋alpha通道。

+0

感謝隊友,我可能會堅持我目前的狀況,但這是一個很好的選擇。乾杯 –

+0

歡迎您:) –

+0

它看起來不錯。但是這個問題是你的'h1'變暗了。 –

1

您也可以使用多背景:

.slide { 
    background-image: linear-gradient(rgba(0, 0, 0, 0.2), rgba(0, 0, 0, 0.2)),            
         url('/assets/img/bg-cover.jpg') 
    background-size: cover 
} 
相關問題