元素水平垂直居中常用方法汇总

909 阅读1分钟

行内元素

<div class="demo1">1111</div
.demo1 {
  width: 100px;
  height: 30px;
  border: 1px solid #333;
}

line-height + text-align

.demo1 {
  /* 水平居中 */
  text-align: center;
  /* 垂直居中: line-height = height */
  line-height: 30px;
}

行内块状元素

line-height + vertical-align + text-align

vertical-align 只能应用在行内元素和单元格元素上。

<div class="demo1">
  <img src="https://dss2.bdstatic.com/6Ot1bjeh1BF3odCf/it/u=1765461753,2420530801&fm=218&app=92&f=PNG?w=121&h=75&s=A7D53F6EC4F07F803ADE5F7D0300D07C">
</div>
.demo1 {
  width: 500px;
  height: 200px;
  border: 1px solid #333;
  /* 关键代码 */
  text-align: center;
  line-height: 200px;
}

img {
    vertical-align: middle;
}

display: table/table-cell + vertical-align + text-align

<div class="demo1">
  <div class="content">
    <p>1111111</p>
    <p>2222222</p>
  </div>
</div>
.demo1 {
  width: 500px;
  height: 200px;
  border: 1px solid #333;
  /* 关键代码 */
  display: table;
}

.content {
  vertical-align: middle;
  display: table-cell;
  text-align: center;
}

块状元素

<div class="parent">
    <div class="child"></div>
</div>

position + margin

.parent {
    position: relative;
}
.child {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    margin: auto;
}

flex + margin

.parent {
    display: flex;
    /* 定义项目在主轴上如何对齐 */
    justify-content: center;
    /* 定义项目在交叉轴上如何对齐 */
    align-items: center;
}

或者

.parent {
  display:flex;
}
.child {
  margin: auto;
}

grid

.parent {
    display: grid;
}
.child {
    justify-self: center;
    align-self: center;
}

或者

.parent {
    display:grid;
}
.child {
    margin: auto;
}

transform + position

.parent {
    position: relative;
}

.child {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}