### 1. 重置瀏覽器字體大小
先重置瀏覽器預設值,再重設字體大小。若不想下載龐大的 YUI 重置檔,可用以下精簡版:
body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,form,fieldset,input,textarea,p,blockquote,th,td { margin:0; padding:0; }
table { border-collapse:collapse; border-spacing:0; }
fieldset,img { border:0; }
address,caption,cite,code,dfn,em,strong,th,var { font-style:normal; font-weight:normal; }
ol,ul { list-style:none; }
caption,th { text-align:left; }
h1,h2,h3,h4,h5,h6 { font-size:100%; font-weight:normal; }
q:before,q:after { content:""; }
abbr,acronym { border:0; }
接著把字體大小重設為 10px:html { font-size: 62.5%; }
如此一來 1em = 10px,之後可依需求調整,例如 h1 { font-size: 2em; } 即 20px。
### 2. 水平居中
大多數網站為固定寬度,水平居中可寫成:
div#container { margin: 0 auto; }
### 3. 控制定位:絕對 vs 相對
若有 :
若內層 div 的 position 為 absolute,則相對於文件左上角定位;
若內層 div 的 position 為 relative,則 left/top 相對於外層 div 的左上角計算。
### 4. 將重要元素置中
div.popup { height:400px; width:500px; position:absolute; top:50%; left:50%; }
div.popup { margin-top:-200px; margin-left:-250px; }
必須明確指定寬高,再把 top/left 設為一半,並用負 margin 補回,即可回到畫面正中央。
### 5. 可重複利用的規則
.left { float: left; }
.right { float: right; }
img.left { border:2px solid #aaaaaa; margin: 0 10px 0 0; }
img.right { border:2px solid #aaaaaa; margin: 0 0 0 10px; padding: 1px; }
建立自己的 CSS 樣式表後,需要時直接套用 class 即可。
### 6. 解決 IE6 浮動元素雙倍邊距
當 div 設了 float:left 與 margin-left:100px 時,IE6 會出現雙倍邊距 bug,
只需多加一個 display:inline 即可:
div { float:left; margin:40px; display:inline; }
### 7. 簡單的導覽選單
HTML:
CSS:
#navbar ul li { display:inline; margin:0 10px 0 0; }
#navbar ul li a { color:#333; display:block; float:left; padding:5px; }
#navbar ul li a:hover { background:#eee; color:black; }
### 8. 不使用 table 的表單
HTML:
CSS:
form div { clear:left; display:block; width:400px; zoom:1; margin:5px 0 0 0; padding:1px 3px; }
form div label { display:block; float:left; width:130px; padding:3px 5px; margin:0 0 5px 0; text-align:right; }
### 9. 讓 footer 永遠停在頁面底部
HTML:
CSS:
html, body { height: 100%; }
#nonFooter { position: relative; min-height: 100%; }
* html #nonFooter { height: 100%; }
#content { padding-bottom: 9em; }
#footer { position: relative; margin-top: -7.5em; }
### 10. 在同一元素上使用多個 class
.red { color: red; }
.bold { font-weight: bold; }
可複用:這段文字同時是紅色且粗體!