這 10 招涵蓋字體縮寫、多 Class 組合、邊框預設值、IE Hack、圖片替換文字、盒模型替代方案、水平/垂直置中、容器定位、背景延伸底部,每一招都是實戰總結。
/* 冗長 */
font-size: 1em;
line-height: 1.5em;
font-weight: bold;
font-style: italic;
font-variant: small-caps;
font-family: Verdana, serif;
/* 縮寫:至少要有 font-size 與 font-family */
font: 1em/1.5em bold italic small-caps Verdana, serif;
順序:font-style | font-variant | font-weight | font-size/line-height | font-family。缺漏值用初始值。
<p class="lead highlight">同時套用 .lead 與 .highlight 樣式</p>
.btn .btn-primary .btn-lg)。/* 只寫樣式,寬度預設 medium(~3px),顏色預設 currentColor (文字色) */
border: solid; /* 3px 實線,文字色 */
border: dashed #c00; /* 3px 虛線,紅色 */
border: 2px dotted; /* 2px 點線,文字色 */
若預設剛好是你要的效果,連寬度/顏色都能省略。
.box {
margin-top: 3.5em !important; /* 現代瀏覽器:3.5em */
margin-top: 2em; /* IE6-7:2em */
}
!important 的特性,無需額外 Hack 檔案即可區隔樣式。> 也被 IE6-7 忽略,可作為區隔手段。目標:顯示設計字體標題,但 HTML 保留真實文字供搜尋引擎/螢幕閱讀器。
<h1 class="logo">Buy widgets</h1>
.logo {
width: 300px; height: 80px;
background: url(logo.png) no-repeat;
text-indent: -9999px; /* 將文字推出視窗 */
overflow: hidden; /* 防止長文字溢出 */
white-space: nowrap; /* 防止換行導致文字露出 */
}
<img alt="Buy widgets">:搜尋引擎權重更高、無障礙更完整。@font-face 載入 Web Font、font-display: swap,直接用真實文字。IE6 盒模型將 padding/border 算入 width 內。不寫 Hack,改用兩層結構:
/* CSS */
#box { width: 150px; } /* 外層設總寬 */
#box div { border: 5px; padding: 20px; } /* 內層放邊框內距 */
/* HTML */
<div id="box"><div>內容</div></div>
box-sizing: border-box 一勞永逸。#content {
width: 700px;
margin: 0 auto; /* 左右自動外距 = 置中 */
}
/* IE6-7 需在 body 加 text-align:center,再在 #content 重置 text-align:left */
body { text-align: center; }
#content { text-align: left; margin: 0 auto; }
line-height === height(如 height: 2em; line-height: 2em;)。.vertical-center {
position: absolute;
top: 50%;
height: 100px;
margin-top: -50px; /* 高度一半負值 */
}
.parent { display: flex; align-items: center; justify-content: center; }
/* 或 */
.parent { display: grid; place-items: center; }
#container { position: relative; } /* 建立定位上下文 */
#navigation {
position: absolute;
left: 30px; top: 5px; /* 相對 #container 定位 */
}
position !== static 祖先定位。<body>(初始包含塊)。CSS 無法直接讓側邊欄高度跟隨主內容,經典欺騙法:
body {
background: url(sidebar-bg.png) repeat-y 0 0; /* 寬度 = 側邊欄寬,顏色 = 側邊欄背景 */
}
#sidebar { width: 200px; float: left; }
#content { margin-left: 200px; }
px,無法用 em/rem 自適應字體縮放。display: flex; min-height: 100vh; 真正等高欄,或 grid-template-columns: 200px 1fr;。這 10 招密技雖部分為歷史經驗,但背後的 CSS 機制理解(盒模型、定位、視覺格式化模型)永不過時。