Catalog
  1. 1. 水平居中的解决方案
    1. 1.1. inline-block + text-align
    2. 1.2. table + margin
    3. 1.3. absolute + transform
    4. 1.4. flex + justify-content
  2. 2. 垂直居中的解决方案
    1. 2.1. table-cell + vertical-align
    2. 2.2. absolute + transform
    3. 2.3. flex + align-items
  3. 3. 水平垂直居中
    1. 3.1. inline-block + text-align + table-cell + vertical-align
    2. 3.2. absolute + transform
    3. 3.3. flex + justify-content + align-items
CSS各种居中解决方案

以下解决方案都为不定宽和高的情况下,结构如下:

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

水平居中的解决方案

inline-block + text-align

.parent{
text-align: center;
}
.child{
display: inline-block;
}

table + margin

.child{
display: table;
margin: 0 auto;
}

absolute + transform

.parent{
position: relative;
}
.child{
position: absolute;
left: 50%;
transform: translateX(-50%);
}

flex + justify-content

.parent{
display: flex;
justify-content: center;
}

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

垂直居中的解决方案

table-cell + vertical-align

.parent{
display: table-cell;
vertical-align: middle;
}

absolute + transform

.parent{
position: relative;
}
.child{
position: absolute;
top: 50%;
transform: translateY(-50%);
}

flex + align-items

.parent{
display: flex;
align-items: center;
}

水平垂直居中

inline-block + text-align + table-cell + vertical-align

.parent{
text-align: center;
display: table-cell;
vertical-align: middle;
}
.child{
display: inline-block;
}

absolute + transform

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

flex + justify-content + align-items

.parent{
display: flex;
justify-content: center;
align-items: center;
}
Author: 匡凡
Link: https://kuangfan.github.io/2019/12/16/css/css%E5%90%84%E7%A7%8D%E5%B1%85%E4%B8%AD%E8%A7%A3%E5%86%B3%E6%96%B9%E6%A1%88/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.
Donate
  • 微信
  • 支付宝