「圖片定位以 left、top 設定位置」——最佳回答精準指出關鍵。
absolute 定位的參考點是**最近的非 static 定位祖先元素**。父容器 relative 不脫離文檔流,子元素 absolute 脫離文檔流並相對父容器定位。
<div class="container">
<img src="logo.png" class="overlay" alt="Logo">
</div>
<style>
.container {
position: relative; /* 關鍵:建立定位基準 */
width: 300px;
height: 300px;
background: #ff0;
}
.overlay {
position: absolute;
left: 100px; /* 相對 container 左邊 100px */
top: 200px; /* 相對 container 頂部 200px */
width: 50px;
height: 50px;
}
</style>
| 現象 | 原因 | 修正 |
|---|---|---|
| 圖片跑到頁面左上角 | 父容器未設 relative,參考點變成 body | 父容器加 position: relative |
| right/bottom 無效 | 未設定寬高,或圖片本身有預設 margin | 設定 width/height、margin: 0 |
| 圖片被截斷 | 父容器 overflow: hidden | 移除或改 overflow: visible |
| z-index 不生效 | 父容器建立了堆疊上下文 | 調整父/子 z-index 層級 |
.overlay {
position: absolute;
left: 10%; /* 百分比相對父容器寬度 */
top: 20%;
transform: translate(-50%, -50%); /* 以圖片中心點對齊 */
}
.container {
display: flex;
justify-content: flex-start; /* 或 center, flex-end */
align-items: flex-start;
/* 子元素直接用 margin 微調,無需 absolute */
}
現代佈局優先使用 Flex/Grid,僅在「脫離文檔流、重疊層級」場景用 absolute。