原始 CSS 代碼
#bg {
display: none;
position: absolute;
top: 0%; left: 0%;
width: 100%; height: 100%;
background-color: black;
z-index: 1001;
-moz-opacity: 0.7;
opacity: .70;
filter: alpha(opacity=70);
}
#show {
display: none;
position: absolute;
top: 25%; left: 22%;
width: 53%; height: 49%;
padding: 8px;
border: 8px solid #E8E9F7;
background-color: white;
z-index: 1002;
overflow: auto;
}
逐行中文註釋翻譯
遮罩層 `#bg` (背景蒙版)
| 屬性 | 值 | 中文含義 |
| `display` | `none` | 默認隱藏,JS 控制顯示 |
| `position` | `absolute` | 絕對定位,脫離文檔流 |
| `top` / `left` | `0%` | 貼齊視口左上角 |
| `width` / `height` | `100%` | 鋪滿整個視口 |
| `background-color` | `black` | 黑色背景 |
| `z-index` | `1001` | 層級高於普通內容,低於彈窗內容層 |
| `opacity` | `.70` | 70% 不透明度(30% 透明),標準寫法 |
| `-moz-opacity` | `0.7` | Firefox 老版本私有前綴 |
| `filter` | `alpha(opacity=70)` | IE 8- 專用濾鏡實現透明度 |
彈窗內容層 `#show`
| 屬性 | 值 | 中文含義 |
| `display` | `none` | 默認隱藏 |
| `position` | `absolute` | 絕對定位 |
| `top` / `left` | `25%` / `22%` | 垂直 25%、水平 22% 位置,近似居中偏左上 |
| `width` / `height` | `53%` / `49%` | 佔視口約一半大小 |
| `padding` | `8px` | 內邊距 8px |
| `border` | `8px solid #E8E9F7` | 8px 實線邊框,淡藍灰色 |
| `background-color` | `white` | 白色背景 |
| `z-index` | `1002` | 層級高於遮罩層,確保顯示在最上層 |
| `overflow` | `auto` | 內容超出時顯示滾動條 |
經典彈窗結構對應 HTML
<div id="bg"></div> <!-- 遮罩層 -->
<div id="show"> <!-- 彈窗內容 -->
<h2>標題</h2>
<p>內容...</p>
<button onclick="closeDialog()">關閉</button>
</div>
JS 控制顯示/隱藏
function openDialog() {
document.getElementById('bg').style.display = 'block';
document.getElementById('show').style.display = 'block';
}
function closeDialog() {
document.getElementById('bg').style.display = 'none';
document.getElementById('show').style.display = 'none';
}
現代化改進建議
- 使用 `fixed` 替代 `absolute`:防止頁面滾動時彈窗位移,`position: fixed; top: 0; left: 0;`。
- 統一透明度寫法:僅保留 `opacity: 0.7;`,現代瀏覽器全支持,移除 `-moz-` 和 `filter`。
- Flex/Grid 居中:遮罩層內用 `display: flex; justify-content: center; align-items: center;` 彈窗自動居中,無需手動計算 `top/left`。
- 語義化 class 替代 id:`.modal-overlay`、`.modal-content` 便於復用多個彈窗。
- 無障礙屬性:`role="dialog"`、`aria-modal="true"`、`aria-labelledby="title-id"`。
現代寫法示例
.modal-overlay {
display: none;
position: fixed; inset: 0; /* 等同 top/left/right/bottom: 0 */
background: rgba(0, 0, 0, 0.7); /* 替代 opacity + 背景色 */
z-index: 1000;
}
.modal-overlay.show { display: flex; } /* JS 切換 .show 類 */
.modal-content {
width: 50%; max-width: 600px;
background: white;
border-radius: 8px;
padding: 20px;
overflow: auto;
max-height: 80vh;
/* Flex 容器自動居中,無需 margin 計算 */
}
總結
該 CSS 實現經典「遮罩+彈窗」模式。理解 `z-index` 層級關係、`absolute/fixed` 定位差異、跨瀏覽器透明度寫法,是前端基礎功。現代項目建議遷移至 `fixed` + `flex` + `rgba` + `class` 切換的更簡潔、健壯方案。