CSS 設置背景透明度,不影響子元素


由於 opacity 屬性能被子元素繼承,使用它設置父元素背景透明度時也會影響子元素.

解決方法:

1> 使用 RGBA

Example

1 .classname {
2     /* RGBa, 透明度0.6 */
3  background: rgba(0, 0, 0, 0.6);
4 }

2> 使用 opacity, 設置一個背景DIV,此DIV使用絕對布局

Example

1 <div class="demo"> 2  <div class="demo-bg"></div><!-- 透明背景 --> 3  <div class="demo-txt">Content here</div><!-- 不透明文字 --> 4 </div>

Demo

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4 <meta charset="utf-8">
 5 <title>opacity</title>
 6 <style>
 7 *{
 8  padding: 0;
 9  margin: 0;
10 }
11 body{
12  padding: 50px;
13  background: url(http://static.cnblogs.com/images/logo_small.gif) 0 0 repeat;
14 }
15  
16 .demo{
17  width: 200px;
18  height: 200px;
19  position: relative;
20 }
21 .demo-bg{
22  position: absolute;
23  left: 0;
24  top: 0;
25  z-index: 0;
26  width: 200px;
27  height: 200px;
28  background-color:#000000;
29  filter:Alpha(opacity=50);
30  background-color: rgba(0,0,0,0.5);
31 }
32 .demo-txt{
33  position: relative;
34  z-index: 1;
35  color: #FFFFFF;
36 }
37 </style>
38 </head>
39 <body>   
40  
41 <div class="demo">
42     <div class="demo-bg"></div><!-- 透明背景 -->
43     <div class="demo-txt">Content here</div><!-- 不透明文字 -->
44 </div>
45  
46 </html>
View Code

3> 建立一個24位PNG背景圖片

不推薦,IE下24位PNG圖透明時引起的內存泄漏.

SEE ALSO

CSS實現背景透明完美解決方案
CSS實現背景透明,文字不透明,兼容所有瀏覽器


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM