現象:IE6/7 邊框部分消失、背景截斷
根因:hasLayout = false,元素未建立渲染上下文
解法:觸發 hasLayout — zoom: 1 / width: 100% / height: 1% / display: inline-block
現代視角:標準模式 + box-sizing: border-box 徹底消滅此類問題
核心原理:浮動元素脫離文檔流 → 父容器高度塌陷為 0
清除浮動四大法:
/* 1. 額外標籤法 (不推薦,汙染 HTML) */
<div class="clear"></div> .clear { clear: both; }
/* 2. Overflow 法 (副作用:剪裁陰影/absolute 子元素) */
.parent { overflow: hidden; zoom: 1; } /* zoom 觸發 IE hasLayout */
/* 3. 偽元素法 (推薦,語義純粹) */
.clearfix::after {
content: "";
display: table; /* 或 block */
clear: both;
}
.clearfix { zoom: 1; } /* IE6/7 */
/* 4. Flex/Grid 現代法 (徹底方案) */
.parent { display: flex; } /* 或 grid */
/* 子元素 float 自動失效,容器自動包裹 */
IE6 三像素 Bug:浮動元素旁邊的文本行盒產生 3px 神秘間隙
解法:給文本容器設置 height: 1% 或 zoom: 1 觸發 hasLayout,或現代佈局棄用 float。
行高陷阱:line-height: normal 瀏覽器計算不一(1.1-1.3),導致垂直對齊偏差
黃金法則:body { line-height: 1.5; } 顯式設置無單位值,子元素按比例繼承。
經典 clearfix 終極版:
.clearfix::after {
content: "";
display: table; /* table 比 block 更穩,避免 margin 塌陷 */
clear: both;
}
.clearfix { *zoom: 1; } /* IE6/7 hack */
/* 現代簡化版 (IE10+) */
.flow-root { display: flow-root; } /* 專門建立 BFC,語義最清晰 */
核心哲學:理解文檔流 → 浮動 → 定位 → Flex → Grid的演進邏輯,順勢而為而非對抗瀏覽器。
顯示類型本質:
| 類型 | 典型標籤 | 盒模型 | 流向 |
|---|---|---|---|
| 塊級 | div, p, h1-h6, section | 完整盒模型 | 垂直堆疊 |
| 行內 | span, a, strong, em | 僅水平 padding/margin/border | 水平排列 |
| 行內塊 | img, input, button | 完整盒模型 + 水平排列 | 水平排列 |
| 重置 | * { display: block; } | 統一為塊級 | 破壞語義,慎用 |
/* 圖文混排垂直居中方案 */
.img-link {
display: inline-flex;
align-items: center;
gap: 0.5rem;
padding: 0.25rem 0.5rem;
}
.img-link img { vertical-align: middle; } /* 兼容舊瀏覽器 */
IE6 雙邊距 Bug:float: left; margin-left: 10px → 實際 20px
修復:display: inline(不影響浮動行為,僅修正邊距計算)
行內塊間隙來源:HTML 換行符被渲染為空白字符
/* 方案 1:HTML 緊湊寫法 */
<ul><li>1</li><li>2</li></ul>
/* 方案 2:字體大小為 0 */
ul { font-size: 0; }
li { font-size: 1rem; display: inline-block; }
/* 方案 3:負 margin (不推薦) */
li { margin-right: -4px; }
/* 方案 4:Flex/Grid 現代方案 (最佳) */
ul { display: flex; gap: 1rem; }
這 10 條口訣是 Float 時代的結晶。現代開發應建立新認知體系:
margin-inline-start 適配 RTL/LTR 書寫模式口訣易記,原理易懂,但現代佈局工具才是生產力的真正解放者。