1 居中文本

1.1 居中单行文本

1.1.1 line-height = height

<div style="height: 100px; line-height: 100px; background-color: #F2C679">
    垂直居中
</div>

效果

垂直居中

1.2 居中多行文本

1.2.1 display: flex + align-items: center

  • 同时适用于“居中单个子元素”。见3.1.1

  • 同时适用于“居中多个子元素”。见3.2.2

<div style="height: 100px; display: flex; align-items: center; background-color: #F2C679;">
    垂直居中<br />垂直居中
</div>

效果

垂直居中
垂直居中

1.2.2 (父)display: table + (子)display: table-cell; vertical-align: middle;

<div style="display: table; height: 100px;">
    <div style="display: table-cell; vertical-align: middle; background-color: #F2C679;">
        垂直居中<br/>垂直居中
    </div>
</div>

效果

垂直居中
垂直居中

2 居中自身

3 居中子元素

3.1 单个子元素

3.1.1 (父)display: flex + align-items: center

  • 同时适用于“居中多行文本”。见1.2.1
  • 同时适用于“居中多个子元素”。见3.2.2
<div style="height: 100px; display: flex; align-items: center; background-color: #F2C679;">
    <div style="height: 60px; background-color: #e8952e;">垂直居中</div>
</div>

效果

垂直居中

3.1.2 (父)display: flex + flex-direction: column + justify-content: center

  • 同时适用于“居中多个子元素”。见3.2.1
<div style="height: 100px; display: flex; flex-direction: column; justify-content: center; background-color: #F2C679;">
    <div style="height: 60px; background-color: #e8952e;">垂直居中</div>
</div>

效果

垂直居中

3.1.3 (父)指定height + position: relative + (子)position: absolute; top: 50%; transform: translateY(-50%);

<div style="height: 100px; position: relative; background-color: #F2C679;">
    <div style="height: 60px; position: absolute; top: 50%; transform: translateY(-50%); background-color: #e8952e;">
        垂直居中
    </div>
</div>

效果

垂直居中

3.1.4 (父)指定height + position: relative + (子)position: absolute; top: 0; bottom: 0; margin: auto 0;

<div style="height: 100px; position: relative; background-color: #F2C679;">
    <div style="height: 60px; position: absolute; top:0; bottom: 0; margin: auto 0; background-color: #e8952e;">
        垂直居中
    </div>
</div>

效果

垂直居中

3.2 多个子元素

3.2.1 (父)display: flex + flex-direction: column + justify-content: center

  • 见3.1.2
<div style="height: 280px; display: flex; flex-direction: column; justify-content: center; background-color: #F2C679;">
    <div style="height: 60px; background-color: #e8952e;">垂直居中</div>
    <div style="height: 60px; background-color: #ea390f;">垂直居中</div>
</div>

效果

垂直居中
垂直居中

3.2.2 (父)display: flex + align-items: center

  • 同时适用于“居中多行文本”。见1.2.1
  • 同时适用于“居中单个子元素”。见3.1.1
<div style="height: 100px; display: flex; align-items: center; background-color: #F2C679;">
    <div style="height: 60px; background-color: #e8952e;">垂直居中</div>
    <div style="height: 40px; background-color: #ea390f;">垂直居中</div>
    <div style="height: 80px; background-color: #e8952e;">垂直居中</div>
</div>

效果

垂直居中
垂直居中
垂直居中