行内级元素

设置 text-align: center;

块级元素

(1)设置宽度;

(2)设置 margin: 0 auto;

原理:margin-left 和 margin-right 都为 auto ,左右部分的margin自动分配,元素左右margin的值相等,就使元素水平居中。

参考自W3C官方文档

10.3.3 Block-level, non-replaced elements in normal flow

If both ‘margin-left’ and ‘margin-right’ are ‘auto’, their used values are equal. This horizontally centers the element with respect to the edges of the containing block.

👉 https://www.w3.org/TR/CSS21/visudet.html#blockwidth