CSS 技巧累積靠實戰,本文整理 12 個高頻實用片段,涵蓋重置、佈局、文字處理、表單、列印等場景,每個都附帶可直接複製的代碼與適用情境說明。
a:focus { outline: none; }
⚠️ 無障礙建議:改用 outline: 2px solid transparent 搭配 box-shadow 保持鍵盤可見焦點。
* { margin: 0; padding: 0; box-sizing: border-box; }
現代專案建議改用 Normalize.css。
a { white-space: nowrap; }
長連結建議搭配 text-overflow: ellipsis 截斷。
html { overflow-y: scroll; }
跨瀏覽器替代方案:
html, body { min-height: 100%; }
.single-line {
height: 48px;
line-height: 48px;
}
條件:固定高度、單行文字、無內距干擾。
.clearfix::after {
content: "";
display: table;
clear: both;
}
現代替代:父容器加 display: flow-root 或 overflow: hidden(注意副作用)。
.center-block {
width: 800px;
margin: 0 auto;
}
IE6/7 相容:父層 text-align: center + 子層 text-align: left + display: inline-block。
textarea { overflow: auto; }
h2 { page-break-before: always; }
其他值:avoid(避免分頁)、left/right(指定左/右頁)。
.ellipsis {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.break-word { word-wrap: break-word; } /* 舊屬性名 */
.overflow-wrap { overflow-wrap: anywhere; } /* 現代標準 */
img { display: block; }
/* 或 */
img { vertical-align: middle; }
/* 或父層 */
figure { font-size: 0; line-height: 0; }
掌握實用技巧後,建議深入 CSS Position 定位完整指南,攻克最讓人頭痛的定位屬性。