在 Firefox、Chrome 這類現代瀏覽器上,background-color: rgba(...) 就能優雅地做到背景半透明而文字清晰。真正的麻煩來自 IE6/7/8——它們完全不認 rgba,只能用私有濾鏡 filter: Alpha。
而 filter: Alpha 有個副作用:它跟 opacity 一樣會把子內容一起變透明。破解方式是在子節點上補一個 position: relative,讓它不繼承父層的透明濾鏡。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>背景透明、文字不透明</title>
<style type="text/css">
.warp {
background: #eee url(back.jpg) no-repeat left top;
width: 440px; height: 400px;
border: 1px solid #ccc;
}
.content {
width: 180px; height: 260px;
margin: 0 auto; padding: 30px;
background: rgba(255, 255, 255, 0.6) !important;
filter: Alpha(opacity=60);
background: #fff; /* 給不認 rgba 的 IE 預備 */
}
.content p { position: relative; } /* 讓文字逃脫 IE 的透明濾鏡 */
</style>
</head>
<body>
<div class="warp">
<div class="content">
<p>這是一段示範文字,用來驗證半透明底板上的文字是否保持清晰。</p>
</div>
</div>
</body>
</html>
屬性撰寫順序很重要:rgba 要放在最後並帶 !important,讓支援的瀏覽器優先採用;不支援的自然會忽略它,退回到上一行的純色背景與 Alpha 濾鏡。
其次,.content p 的 position: relative 不能省,這正是 IE 下文字保持不透明的關鍵。最後記得只對文本節點以外的子元素這樣處理。
這套寫法在 IE6 以上、Firefox、Opera、Chrome、Safari 都有人驗證通過,屬於那個年代的標準兼容解法。