Skip to main content

元素的水平居中

Docs

在一些需求中,需要元素在父元素中水平居中显示(父元素一般都是块级元素、inline-block)

  • 行内级元素 (包括 inline-block 元素)

    • 水平居中:在父元素中设置 text-align: center
  • 块级元素

    • 水平居中:margin: 0 auto

使用margin: 0 auto

你可以使用 margin: 0 auto 属性把左右外边距设置为 自动 来让整体容器居中:

div {
margin: 0 auto;
width: 200px; /*容器的宽度*/
}

使用display: flex

你也可以使用 display: flex 属性来让容器居中:

div {
display: flex;
justify-content: center;
}

使用position: fixed

你还可以使用 position: fixed 属性来让元素固定在你指定的位置:

div {
position: fixed;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
width: 200px;
}