4.1 absolute positioning
在CSS中,absolute positioning(絕對定位)讓你可以精確控制網頁上元素的位置。使用絕對定位時,元素會從文檔的正常流中移除並相對於最近的已定位祖先進行定位。如果沒有這樣的祖先,元素將相對於初始容器(通常是 <html>
或 <body>
)進行定位。
絕對定位的主要特點:
- 移除文檔流:絕對定位的元素不影響其他元素,且不在計算父元素尺寸時考慮。
-
相對於祖先定位:元素相對於最近的具有相對 (
position: relative
)、絕對 (position: absolute
)、固定 (position: fixed
) 或粘性 (position: sticky
) 定位的祖先定位。 -
使用座標:使用
top
、right
、bottom
和left
屬性來設置元素的精確位置。
基本絕對定位範例
讓我們看一個帶有絕對定位元素的簡單範例:
CSS
.container {
position: relative;
width: 300px;
height: 300px;
background-color: lightgrey;
}
.box {
position: absolute;
top: 50px;
left: 50px;
width: 100px;
height: 100px;
background-color: deepskyblue;
}
HTML
<div class="container">
<div class="box">Absolute Box</div>
</div>
在這個範例中,元素 .box
相對於父容器 .container
進行定位,這個容器具有 position: relative;
。
4.2 建立覆蓋層 (overlays)
絕對定位常用於創建覆蓋層,例如模態窗口、彈出提示和燈箱。
絕對定位範例:
CSS
.wrapper {
min-height: 300px;
}
.overlay {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
}
.modal {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: white;
padding: 20px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}
HTML
<div class="wrapper">
<div class="overlay">
<div class="modal">
<p>Modal Content</p>
</div>
</div>
</div>
4.3 精確佈局和界面組件
絕對定位對於創建精確的佈局非常有用,例如媒體播放器中的控制元素、自定義控制元件和工具條。
絕對定位範例:
CSS
.player {
position: relative;
width: 400px;
height: 50px;
background-color: #333;
color: white;
}
.play-button {
position: absolute;
left: 10px;
top: 50%;
transform: translateY(-50%);
}
.volume-control {
position: absolute;
right: 10px;
top: 50%;
transform: translateY(-50%);
}
HTML
<div class="player">
<div class="play-button">Play</div>
<div class="volume-control">Volume</div>
</div>
4.4 創建複雜佈局
絕對定位允許創建複雜的佈局,例如信息面板和交互式元素。
絕對定位範例:
CSS
.dashboard {
position: relative;
width: 800px;
height: 600px;
background-color: #f0f0f0;
}
.sidebar {
position: absolute;
top: 0;
left: 0;
width: 200px;
height: 100%;
background-color: #333;
color: white;
}
.main-content {
position: absolute;
top: 0;
left: 200px;
width: calc(100% - 200px);
height: 100%;
background-color: #fff;
}
HTML
<div class="dashboard">
<div class="sidebar">Sidebar</div>
<div class="main-content">Main Content</div>
</div>
GO TO FULL VERSION