要讓一個 `
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>DIV 浮動覆蓋示範</title>
<style>
.container { position: relative; width: 500px; height: 300px; margin: 50px auto; border: 2px solid #333; }
.bottom { width: 100%; height: 100%; background: #3498db; color: #fff; display: flex; align-items: center; justify-content: center; font-size: 24px; }
.top {
position: absolute;
top: 50px; left: 50px;
width: 200px; height: 150px;
background: rgba(231, 76, 60, 0.9);
color: #fff;
display: flex; align-items: center; justify-content: center;
font-size: 20px;
z-index: 10;
box-shadow: 0 4px 12px rgba(0,0,0,0.2);
}
</style>
</head>
<body>
<div class="container">
<div class="bottom">底層 DIV (相對定位容器)</div>
<div class="top">浮動覆蓋的 DIV (絕對定位)</div>
</div>
</body>
</html>
| 屬性 | 父容器 (.container) | 浮動層 (.top) |
|---|---|---|
| position | relative(建立定位上下文) | absolute(脫離文件流) |
| top/left | — | 相對父容器定位 |
| z-index | 預設 auto (0) | 大於父/同層元素(如 10) |
.fixed-overlay {
position: fixed; /* 相對視窗定位 */
top: 20px; right: 20px;
z-index: 9999; /* 最高層級 */
}
.grid-stack {
display: grid;
}
.grid-stack > * {
grid-area: 1 / 1; /* 所有子元素佔據同一格,疊在一起 */
}
.top-layer { z-index: 1; }