首先要說明的是背景是內容的祖先元素。如果是兄弟節點那就沒有必要記錄這篇文章了。
記錄一下,知其然也知其所以然。
IE8-特點:
1.不支持"opcity:0.5;"這種寫法,只支持"filter:alpha(opacity=50)"。
2.如果背景元素擁有css屬性設置了z-index的值(除默認值auto外),則內容會隨着背景元素一起半透明
3.如果背景元素的內容元素本身或其祖先節點(這些祖先節點是背景元素的后代節點)沒有設置css定位屬性position:relative/absolute/fixed。則內容也會隨着背景元素一起半透明。
4.支持"background:rgb(0,0,0)"設置背景顏色,但是不支持“background:rgba(0,0,0,0.5)”這種設置背景顏色的同事設置半透明的方式。
IE9+、chrome、Firefox特點:
1.支持"opacity:0.5",但是內容會隨背景一起半透明
1.支持“background:rgba(0,0,0,0.5)”這種設置背景顏色的同事設置背景半透明但內容不透明的方式。
2.如果同事使用opacity=0.5和rgba不透明度為0.5,那么效果是在元素為opacity所設置的不透明度的情況下背景再次按rgba的方式半透明。最終背景的半透明度為opacity*rgba=0.5*0.5=0.25。
IE9+還有一個特點就是同時支持opcity:0.5和"filter:alpha(opacity=50)"這種方式。所以rgba和filter一起用會出現第三項的情況。
所以綜合上述的瀏覽器特點,兼容所有瀏覽器的方案是背景元素設置樣式為
/*不能設置z-index,根據情況設置需要的background的顏色,chrome/firefox中第一句起作用;IE中后兩句起作用*/
.background{
background: rgba(0,0,0,0.5);/*firefox、chrome*/
background: #000\9;/*IE*/
filter: alpha(opacity=50);/*IE*/
}
代碼解讀為在Firefox、chrome下后兩句不會被識別,所以使用rgba做背景半透明內容不透明;IE下第二句的background會覆蓋第一句話,所以最終結果是后兩句起到作用。
內容元素的樣式為
/*可以設置元素或其祖先節點為定位樣式relative/absolute/fixed*/
.content{
position:relative;
}
完整實例
<!DOCTYPE html> <html lang="ch-cn"> <head> <meta charset="utf-8"> <style type="text/css"> html,body, div, dl, dt, dd, ul, ol, li, h1, h2, h3, h4, h5, h6, pre, code, form, fieldset, legend, input, button, textarea, p, blockquote, th, td{ margin: 0; padding:0; } *{ -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } /*不能設置z-index,根據情況設置需要的background的顏色,chrome/firefox中第一句起作用;IE中后兩句起作用*/ .background{ background: rgba(0,0,0,0.5);/*firefox、chrome*/ background: #000\9;/*IE*/ filter: alpha(opacity=50);/*IE*/ } /*可以設置元素或其祖先節點為定位樣式relative/absolute/fixed*/ .content{ position:relative; } </style> </head> <body> <div style="width:50px;height:50px;border:1px solid;background: red;"></div> <div class="background" style="width: 200px;height: 200px;"> <div class="content" style="width: 50px;height:50px;background: red;"></div> </div> </html>
效果圖如下

