塊級元素就是那些自為一行的元素,有高度寬度。行內元素沒有高度,行內塊級元素有高度,不換行。
好了,下面用幾個剛剛試驗的例子把這部分知識小記一下,為日后深入學習打基礎。
1.水平居中
- 非塊級元素水平居中:
設置父元素的text-align:center就可以了。
- 塊級元素水平居中:
position不是absolute也不是fixed時(也就是並未脫離文檔流),margin-left=margin-right=auto,塊級元素width不是aoto,就可實現水平居中。

1 <!DOCTYPE html> 2 <html> 3 <meta charset="utf-8"/> 4 <head> 5 <style type="text/css"> 6 #header{ 7 border: 1px solid red; 8 height: 100px; 9 } 10 #container{ 11 border: 1px solid blue; 12 margin:0 auto; 13 width: 300px; 14 height: 300px; 15 text-align: center; 16 } 17 </style> 18 </head> 19 <body> 20 <div id="header" >header</div> 21 <div id="container" > 22 container 23 </div> 24 </body> 25 </html>
2.垂直居中
- 文本垂直居中
如果只有一行本文,設置容器的line-height等於容器height。
#container{ border: 1px solid blue; margin:0 auto; width: 300px; height: 300px; text-align: center; line-height: 300px; }
如果是多行文本至少要再加一個容器box把文本包起來,可以設置box的margin或者其父容器的margin。另一個方法就是使用vertical-align屬性,但這個屬性只對表格元素有效,所以需要設置box父元素display:table,設置box的display:table-cell。
- 塊級元素垂直居中
要借助position和left、top幾個屬性。top表示向下平移,其他同理。position屬性有四個值:
static: 靜態定位,默認值,在文檔流中不移動,此時top等屬性無效。
relative:相對定位,相對自己原本位置定位,不脫離文檔流。
absolute:絕對定位,相對非static父元素定位,脫離文檔流(原來位置被別人占了)。
fixed:固定定位,相對瀏覽器窗口定位,也脫離文檔流,總用做購物車廣告等。
如果要垂直居中的元素設置成絕對定位,top和left在按容器和居中元素大小設置一下就可以了,但前提是父元素是非static的。就像下面這樣。

<!DOCTYPE html> <html> <meta charset="utf-8"/> <head> <style type="text/css"> #header{ border: 1px solid red; height: 100px; } #container{ border: 1px solid blue; margin:0 auto; width: 300px; height: 300px; position: relative; } #content{ position:absolute; top: 100px; left: 100px; background-color: gray; width: 100px; height: 100px; } </style> </head> <body> <div id="header" >header</div> <div id="container" > <div id="content"> content </div> </div> </body> </html>
換幾種情況考慮,如果居中元素是相對定位的,就不要求父元素是非static的了。這固然好,但限制是不方便計算偏移量,偏移量是相對自己原位置算的,如果居中元素上方有兄弟節點也需要考慮進去,麻煩的是如果兄弟節點大小不固定,恐怕只能用腳本動態去算了。如果居中元素是固定定位的呢?考慮了一下,使用固定定位做垂直居中沒有什么特殊的優勢。
3.拉伸
對於行內元素、行內塊級元素、浮動元素、表格及絕對定位元的素:
- left=right=auto,width=auto時是橫向收縮的
- top=bottom=auto,height=auto時,是縱向收縮的
對於塊級元素和絕對定位的元素:
- left=right!=auto,width=auto時是橫向拉伸的
<!DOCTYPE html> <html> <meta charset="utf-8"/> <head> <style type="text/css"> label{ border: 1px solid blue; margin: 1px 0; } div{ border: 1px solid red; margin: 1px 0; } </style> </head> <body> <label>我是橫向收縮的label1</label> <div>我是橫向拉伸的div1</div> </body> </html>
auto通常是默認值,我們看到的非塊級元素橫向縱向多數是收縮的,如圖中label。而塊級元素div默認是橫向拉伸縱向收縮的,如圖中div1。瀏覽器通常會給元素加默認樣式,所以元素並沒有完全與瀏覽器窗口貼上,如果添加*{margin:0;padding:0;}就顯示正常了。
對於絕對定位元素:
- top=bottom=!auto,height=auto時,是縱向拉伸的。
<!DOCTYPE html> <html> <meta charset="utf-8"/> <head> <style type="text/css"> div{ position: absolute; background-color: green; top:0; bottom:0; height:auto; } </style> </head> <body> <div>我是縱向拉伸的div2</div> </body> </html>
auto與100%的尺寸差別