2014-02-19 59 views
24

我試圖將其不透明度重置爲1.0'Demo text 4',其容器的不透明度設置爲0.3。 我讀過,我可以直接使用設置文本:顏色: rgba(255,255,0,1); 但這不適合我。有沒有辦法實現我的目標?如何覆蓋兒童的不透明度

<!DOCTYPE html> 
<html lang="en"> 
<head> 
<style> 
#text_holder { 
background: blue; 
width: 500px; 
height: 200px; 
} 
#text_holder2 { 
background: blue; 
width: 500px; 
height: 200px; 
color: rgba(255, 255, 0, 1); 
} 

#alpha_30 { 
opacity: 0.3; 
color: #ff0000; 
} 
#alpha_100 { 
color: #ff0000; 
} 
</style> 
</head> 

<body> 


<div id="alpha_100"> 
<div id="text_holder"> 
    <p>Demo text 1</p> 
</div> 
</div> 

<div id="alpha_30"> 
<div id="text_holder"> 
    <p>Demo text 2</p> 
</div> 
</div> 

<div id="alpha_30"> 
<div id="text_holder"> 
    <p>Demo text 3</p> 
</div> 


<div id="text_holder2"> 
    <p>Demo text 4</p> 


</div> 

</div> 

</body> 
</html> 
+1

基本上,你不能覆蓋孩子的不透明度。你可能在尋找的答案取決於你實際上想要做什麼。 –

+0

保利是正確的,不透明度影響整個元素(包括孩子),不能被子元素顛倒。你能明確你想做什麼嗎?有辦法解決它。 – badAdviceGuy

+0

我想創建一個背景並應用一個alpha = .5,然後在背景上放置一些文本,但要在alpha = 1處顯示文本。我知道我可以用圖形創建bg,但想知道是否可以用CSS實現相同的效果。 – SimonRH

回答

17

你不行。

如果您使用純色背景色,那麼是使用rgba代替。

#text_holder { 
background:rgba(0, 0, 255,1); 
width: 500px; 
height: 200px; 
} 
#text_holder2 { 
background: rgba(0, 0, 255,1);; 
width: 500px; 
height: 200px; 
color: rgba(255, 255, 0, 1); 
} 

#alpha_30 > div {/* select child */ 
/*opacity: 0.3;*/ 
background:rgba(0, 0, 255,0.3);/* give opacity to bg color only */ 
color: #ff0000; 
} 
#alpha_100 { 
color: #ff0000; 
} 

對於圖像作爲背景,則可能是假的,通過使用在RGBA主背景顏色不透明度。如果你希望背景的不透明度爲0.3,那麼做1 -0.3 = 0.7來設置你的rgba不透明度。

<div class="bg-img"> 
    <p class="text_holder"> some text</p> 
</div> 
.bg-img { 
    background:url(http://lorempixel.com/100/100/abstract); 
} 
.bg-img .text_holder { 
    background:rgba(255,255,255,0.3);/* here white cause body as white background */ 
    } 

這些都是周圍工作:父DIV http://codepen.io/anon/pen/yGgpz

+0

爲什麼不能像所有其他屬性一樣重寫不透明度? – Lee

+0

@你不只喜歡父母是否顯示:無;如果父項是z-index,則內部的任何內容都將被隱藏:1;任何職位子女的價值不會超過Z-索引:1拋開父母的任何同謀。級聯樣式表。第一個單詞告訴CSS如何工作。有一些規則可以重置爲子項(邊框,顏色,背景等),只要它具體的細節不依賴於父項的佈局。如果一個父母被設定爲translucide,那麼它就是整個盒子,包括孩子,否則規則就會失去它的第一個含義。請排除我的平均英語水平。 –