在傳統的 div + CSS 版面中,要讓區塊水平置中,最常見的作法是搭配使用 text-align: center 與 margin: 0 auto 這兩個屬性。
如果只是想快速讓內容置中,可以直接在 body 上設定 text-align,再讓內層 div 使用 margin: 0 auto:
<body style="text-align: center;"> <div style="margin: 0 auto"></div> </body>
為了讓結構與樣式分離,更推薦把樣式寫進 CSS:
<style>
#content{
width: 778px;
margin: 0 auto;
text-align: center;
}
</style>
<div id="content">看看是不是居中了</div>
margin: 0 auto 會讓元素的左右外距自動平均分配,前提是元素必須先有一個明確的寬度(width),瀏覽器才能計算出左右各留多少空間,進而達到置中效果。而 text-align: center 則負責讓區塊內部的文字內容一併居中。兩者搭配,就能完成經典的固定寬度置中版面。