核心 CSS
/* 半透明遮罩層 */
#overlay {
position: fixed; top: 0; left: 0; width: 100%; height: 100%;
background: #000; opacity: 0.5; z-index: 999;
}
/* 不透明內容層 */
#dialog {
position: fixed; top: 50%; left: 50%;
transform: translate(-50%, -50%);
width: 400px; height: 300px;
background: #fff; z-index: 1000;
border-radius: 8px; box-shadow: 0 4px 20px rgba(0,0,0,.2);
}
/* 頁面可滾動,彈層固定 */
body { margin: 0; }
HTML 結構
彈層內容(不透明)
頁面長內容,滾動時彈層不動
關鍵點
position: fixed 相對視口定位,滾動不移動
- 遮罩層
opacity 只影響自身,子元素不繼承透明度
- 內容層
background: #fff 確保不透明