2017-08-25 210 views
1

CSS: set background image with opacity?的答案使用僞元素:after描述了很好的背景不透明度修復。但是,如果父分部具有背景顏色,則透明背景圖像不再顯示,因爲它使用了z-index: -1。我已經嘗試了使用這個基本模型的無數解決方法,但無濟於事。背景圖像不透明度與父背景顏色

以下是示例代碼。請注意,沒有.locations_30 {background:white}它很好。

body { 
 
    background-color: #fefbed; 
 
    color: #444; 
 
    font-family: Helvetica, sans-serif; 
 
    font-size: 16px; 
 
} 
 

 
.locations_20 { 
 
    position: relative; 
 
} 
 

 
.locations_20:after { 
 
    content: ""; 
 
    width: 100%; 
 
    height: 100%; 
 
    display: block; 
 
    position: absolute; 
 
    z-index: -1; 
 
    background-image: url(../background_images/zenrockgarden_mod.jpg); 
 
    background-repeat: no-repeat; 
 
    left: 0%; 
 
    top: 0%; 
 
    background-size: 100% 100%; 
 
    opacity: 0.27; 
 
} 
 

 
.locations_30 { 
 
    background: white; 
 
    width: 800px; 
 
    padding: 75px; 
 
} /*parent division with color will overrun z-index: -1*/
<body> 
 
    <div class="locations_40"> 
 
    <div class="locations_30"> 
 
     <p class="locations_20"> 
 
     Super Sale Event We are happy to offer the following: etc,,, <br> We are happy to offer the following: etc,,, <br> We are happy to offer the following: etc,,, <br> We are happy to offer the following: etc,,, <br> We are happy to offer the following: 
 
     etc,,, <br> We are happy to offer the following: etc,,, <br> 
 
     </p> 
 
    </div> 
 
    </div> 
 
</body>

回答

1

如果您更新.locations_20規則,這樣它會工作

.locations_20 { 
    position: relative; 
    z-index: 0;     /* added */ 
} 

棧片斷

注意,由於圖像並不在所以這裏加載,我加了red.location_20的背景所以我們可以看到它的工作原理

body { 
 
    background-color: #fefbed; 
 
    color: #444; 
 
    font-family: Helvetica, sans-serif; 
 
    font-size: 16px; 
 
} 
 

 
.locations_20 { 
 
    position: relative; 
 
    z-index: 0;     /* added */ 
 
} 
 

 
.locations_20:after { 
 
    content: ""; 
 
    width: 100%; 
 
    height: 100%; 
 
    display: block; 
 
    position: absolute; 
 
    z-index: -1; 
 
    background-image: url(../background_images/zenrockgarden_mod.jpg); 
 
    background-repeat: no-repeat; 
 
    left: 0%; 
 
    top: 0%; 
 
    background-size: 100% 100%; 
 
    opacity: 0.27; 
 
    background-color: red;   /* temp. added so we can see it */ 
 
} 
 

 
.locations_30 { 
 
    background: white; 
 
    width: 800px; 
 
    padding: 75px; 
 
}
<body> 
 
    <div class="locations_40"> 
 
    <div class="locations_30"> 
 
     <p class="locations_20"> 
 
     Super Sale Event We are happy to offer the following: etc,,, <br> We are happy to offer the following: etc,,, <br> We are happy to offer the following: etc,,, <br> We are happy to offer the following: etc,,, <br> We are happy to offer the following: 
 
     etc,,, <br> We are happy to offer the following: etc,,, <br> 
 
     </p> 
 
    </div> 
 
    </div> 
 
</body>