來到今天的主題,假設我在元素上插入 background-image,這時候想調整背景圖片的不透明度,就可以在元素上設定 opacity: 0.5,如下
// HTML
<div class=”image-bg-1">
Lorem Ipsum is simply dummy text of the printing and typesetting industry.
</div>// CSS
.image-bg-1 {
background-size: cover;
background-image: url(…);
opacity: 0.5;
}
果然背景圖片呈現半透明,但是咦?除了圖片外,文字的不透明度也跟著改變了。
其實這是 opacity 的特性之一,opacity 的設定會應用在整個元素,包含元素裡的內容。所以在這裡除了背景圖片,文字也一併套用到 opacity: 0.5。
那麼如果我只想調整背景圖片的不透明度,而不要更動到文字的話,該怎麼辦呢?background 應該可以設定吧?很可惜的是目前還沒有針對 background 屬性設定不透明度的語法,不過這邊介紹一些方法。
Question:
只想改變背景圖片的 opacity 不透明度,且不要修改到文字
Solution:
運用 stacking context 的概念,讓文字與圖片分開在它們自己的 layer,就不會影響到各自的 opacity
Method 1 — 使用圖片標籤 + Position
- 將圖片與文字分開,分成兩個子元素
- 把圖片從 background-image 改成使用 <img> 標籤置入,並設定 opacity
- 使用 position,讓文字在最上層
// HTML
<div class=”image-bg-2">
<img class=”bg” src=”…” alt=””>
<div class=”content”>
Lorem Ipsum is simply dummy text of the printing and typesetting industry.
</div>
</div>// CSS
.image-bg-2 {
position: relative;
}.bg {
width: 100%;
height: 100%;
object-fit: cover;
opacity: 0.5;
}.content {
position: absolute;
top: 0;
left: 0;
}
Method 2 — 僞元素 + Position
- 在父元素建立僞元素,並把置入圖片的任務交給僞元素
- 在僞元素上設定 opacity
- 使用 position
// HTML
<div class=”image-bg-3">
<div class=”content”>Lorem Ipsum is simply dummy text of the printing and typesetting industry.
</div>
</div>// CSS
.image-bg-3 {
position: relative;
}.image-bg-3::before {
content: “”;
display: block;
background-size: cover;
background-image: url(…);
height: 300px;
width: 100%;
opacity: 0.5;
position: absolute;
/* 偏移值皆設為 0,讓僞元素跟父元素一樣大小 */
top: 0;
bottom: 0;
left: 0;
right: 0;
}.image-bg-3 .content {
position: relative;
}
Method 3 — 疊加不透明度層在 background-image 上 + Position
- 圖片設在父元素
- 父元素另建立僞元素,設定 background-color,疊加在父元素上面
- 記得文字也要設定 position
// HTML
<div class=”image-bg-4">
<div class=”content”>Lorem Ipsum is simply dummy text of the printing and typesetting industry.
</div>
</div>// CSS
.image-bg-4 {
position: relative;
background-size: cover;
background-image: url(…);
}.image-bg-4::before {
content: “”;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
background-color: rgba(255, 255, 255, 0.5);
}.image-bg-4 .content {
position: relative;
}
運用這些方法,就可以讓文字不受到 opacity 的影響喔^^