<div class="wrapper">
<button class="action-btn">浮動按鈕</button>
</div>
.wrapper { width: 400px; height: 300px; background: #1f8dd6; }
.action-btn { float: right; height: 50px; width: 100px; line-height: 50px; }
問題:float: right 使按鈕脫離文檔流,垂直置中失效,貼頂對齊。
<div class="wrapper">
<span class="btn-wrapper">
<button class="action-btn">浮動按鈕</button>
</span>
</div>
.btn-wrapper {
float: right;
height: 300px; /* 等於父容器高度 */
line-height: 300px; /* 單行文字/inline-block 垂直置中關鍵 */
}
.action-btn {
display: inline-block; /* 讓 line-height 生效 */
vertical-align: middle; /* 保險 */
float: none; /* 取消浮動,回歸文檔流 */
height: 50px; width: 100px; line-height: 50px;
}
原理:外層 span 浮動並撐滿高度,line-height 建立垂直基線,內層 inline-block 按基線置中。
.wrapper {
width: 400px; height: 300px; background: #1f8dd6;
display: flex;
align-items: center; /* 側軸 (垂直) 置中 */
justify-content: flex-end; /* 主軸 (水平) 靠右 */
}
.action-btn {
height: 50px; width: 100px;
/* 無需 float、無需包裹層、無需 line-height Hack */
}
優點:語義乾淨、零 Hack、支援多按鈕自動分佈 (gap)、響應式友好。
.wrapper {
display: grid;
place-items: center end; /* align-items: center; justify-items: end; */
/* 或精準控制 */
grid-template-areas: "btn";
justify-content: end;
align-content: center;
}
.action-btn { grid-area: btn; }
vertical-align 僅在行內/表格單元格生效,Float 元素生成塊級盒子,無法直接參與行內格式化上下文。clear 管理。| Float 寫法 | Flex 等價寫法 |
|---|---|
float: left | justify-content: flex-start (預設) |
float: right | justify-content: flex-end |
clear: both | 不需要,Flex 容器自動包含 |
| 垂直置中 Hack | align-items: center |
| 等寬分佈 | flex: 1 / gap |
| 聖杯佈局 | flex: 1 + order |
浮動元素垂直置中,**本質是佈局模型不匹配**。現代 CSS 提供 **Flexbox/Grid** 專為對齊分佈設計,一行代碼解決浮動需 20 行 Hack 才能湊合的問題。重構時:移除 float、clear、包裹層、line-height Hack,改用 display: flex; align-items: center; justify-content: flex-end;,代碼量減 80%,可維護性增 10 倍。