這篇把日常開發最常翻的屬性整理成速查表,包含文字、顏色、盒模型與透明度四大部分。
可以寫多個名稱並以逗號分隔,瀏覽器會依序嘗試,採用第一個可用的字型。
p { font-family: '宋體', '黑體', 'Arial'; }
可用長度值(不可為負),或用百分比——百分比是相對於父元素的字級計算。
p { font-size: 14px; }
normal 等同 400,bold 等同 700,也可直接用 100~900 的數值由細到粗指定。
p { font-weight: bold; }
normal 為正常;italic 使用字型本身設計的斜體;oblique 則是讓瀏覽器把直立字體人為傾斜,字型沒有斜體設計時視覺效果會由它接手。
p { font-style: normal; }
p { font-style: italic; }
p { font-style: oblique; }
把多個屬性合併成一行的寫法:
p {
font-style: italic;
font-weight: bold;
font-size: 14px;
line-height: 22px;
font-family: '宋體';
}
/* 縮寫後 */
p { font: italic bold 14px/22px '宋體'; }
none 無裝飾、underline 下劃線、overline 上劃線、line-through 刪除線、blink 閃爍。
h1 { text-decoration: overline; }
h2 { text-decoration: line-through; }
h3 { text-decoration: underline; }
四個參數依次為:水平偏移(必填,可負)、垂直偏移(必填,可負)、模糊半徑(選填)、陰影顏色(選填)。
h1 { text-shadow: 2px 2px 2px #ff0000; }
取值 auto 或長度值。
p { width: 300px; }
div { width: 50%; }
img { height: 200px; }
div { height: 100px; }
可拆成 margin-top / bottom / left / right,也可用縮寫:
div { width: 300px; height: 100px; margin: 10px; }
div { width: 300px; height: 100px; margin: 0 auto; }
同樣可拆成四個方向,順序與 margin 一致。
div { width: 300px; height: 100px; padding: 10px; }
opacity 取 0.0 到 1.0 之間的小數。若要兼顧舊版 IE,需搭配 filter:
div { filter: alpha(opacity=50); } /* IE6-IE8 */
div { opacity: 0.5; } /* 現代瀏覽器 */
以上就是 CSS 常用樣式的整理,建議搭配實作反覆查閱,寫幾次之後自然就記住了。