1. 程式人生 > 其它 >HTML 和 CSS 使元素居中的 7 種方式

HTML 和 CSS 使元素居中的 7 種方式

<!DOCTYPE html>
<html>
  <body>
    <h2 style="text-align: center;">1. CSS "text-align: center;"</h2>
	
    <h2 style="width: fit-content; margin-left: auto; margin-right: auto;">
2. CSS "width: fit-content; margin-left: auto; margin-right: auto;"
</h2> <!-- 需要指定 width 為 fit-content,display 必須為 block(預設),否則 margin-left / margin-right: auto 不生效 --> <header style="display: flex; justify-content: center;"> <h2>3. 放在一個塊元素中,使用 flex 佈局<br/>並指定 CSS "justify-content: center"</h2> </header> <header style="display: flex;"> <div style="flex-grow: 1"></div> <h2>4. 放在一個塊元素中的兩個 div 中間,使用 flex 佈局</h2> <!-- flex 佈局中元素的 flex-grow 預設為 0,即不向外拓寬來填充的父容器中的空間 --> <!-- div 元素的 flex-grow 都設為 1,使它們以同樣的權重向外拓寬,從而把 h2 擠在中間 --> <div style="flex-grow: 1"></div> </header> <table align="center"> <tr> <td> <h2>5. 放在一個 align 為 center 的 table 中 (deprecated)</h2> </td> </tr> </table> <header style="height: 5em;"> <!-- 由於 position absolute,h2 脫離了文件流,父元素需要指定 height 為 h2 佔位置,否則下面的元素就會緊跟著上面的 table 而與 h2 重疊 --> <h2 style="position: absolute; left: 50%; transform: translatex(-50%);"> 6. 使用絕對定位和指定 "left: 50%;" 且<br/>"transform: translatex(-50%);" </h2> </header> <header style="height: 5em;"> <h2 style="position: absolute; left: 50%; width: 20em; margin-left: -10em;"> 7. 使用絕對定位,指定 "left: 50%;",指定寬度<br/>且指定 "margin-left" 為負的寬度的一半 </h2> <!-- 由於 left: 50% 是讓 h2 元素在頁面正中間開始,要用 margin-left 來讓 h2 元素往左移動其一半的寬度來補償。--> <!-- 要使用 margin-left 需要明確 h2 元素的寬度而不能像 transform 那樣使用 50% 來讓瀏覽器自動計算出 h2 的寬度。--> </header> </body> </html>