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>

  

上一篇:CSS Id 和 Class


下一篇:phpspreadsheet常用设置项