首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

CSS 讓一個 DIV 浮動在另一個 DIV 上方完整教學

     編輯:PHP 相關知識

position: absolute 疊層佈局核心技巧

要讓一個 `

` 浮動覆蓋在另一個 `
` 上方,核心在於 **定位上下文** 與 **z-index**。本文提供最簡範例與完整解析。

最簡範例

<!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)
positionrelative(建立定位上下文)absolute(脫離文件流)
top/left—相對父容器定位
z-index預設 auto (0)大於父/同層元素(如 10)

常見陷阱

  • ❌ 父容器未設 `position: relative/absolute/fixed` → 絕對定位相對 `` 而非預期容器
  • ❌ 父/祖先元素有 `z-index` 形成新疊層上下文 → 子元素 `z-index` 無法突破
  • ❌ 使用 `float` 而非定位 → 無法精確控制重疊位置

進階:固定於視窗

.fixed-overlay {
    position: fixed;      /* 相對視窗定位 */
    top: 20px; right: 20px;
    z-index: 9999;        /* 最高層級 */
}

進階:CSS Grid 疊層(現代寫法)

.grid-stack {
    display: grid;
}
.grid-stack > * {
    grid-area: 1 / 1;  /* 所有子元素佔據同一格,疊在一起 */
}
.top-layer { z-index: 1; }
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved