跳到主要内容

css 垂直居中

垂直居中的几种方式

一 绝对定位

1. 已知父子元素高度 + 绝对定位

<div class="father">
<div class="child"></div>
</div>
<style>
.father {
width: 400px;
height: 400px;
background: blue;
position: relative;
}
.child {
width: 200px;
height: 200px;
background: red;
position: absolute;
top: 50%;
margin-top: -100px;
}
</style>

2. translate + 绝对定位

<div class="father">
<div class="child"></div>
</div>
<style>
.father {
width: 400px;
height: 400px;
background: blue;
position: relative;
}
.child {
height: 200px;
background: red;
position: absolute;
top: 50%;
transform: translate(0, -50%);
}
</style>

* translate()

3. margin:auto + 绝对定位

<div class="father">
<div class="child"></div>
</div>
<style>
.father {
width: 400px;
height: 400px;
background: blue;
position: relative;
}
.child {
background: red;
height: 200px;
position: absolute;
margin: auto;
top: 0;
bottom: 0;
/* top 与 bottom 设置相等就行 */
}
</style>

二 padding

父元素设置上下 padding 相等,将子元素挤到中间位置。不能设置父元素高度,除非父元素设置的上下 padding 刚好等于子元素高度

<div class="father">
<div class="child"></div>
</div>
<style>
.father {
background: blue;
padding: 100px 0;
}
.child {
background: red;
height: 200px;
width: 200px;
}
</style>

三 添加占位元素

父元素再添加一个子元素,高度设置为父元素的 50%,然后设置要居中的子元素 margin-top 为高度一半的负数。这个和绝对定位的原理一样。

<div class="father">
<div class="base">base</div>
<div class="child"></div>
</div>
<style>
.father {
width: 400px;
height: 400px;
background: blue;
}
.base {
height: 50%;
background: purple;
}
.child {
background: red;
height: 200px;
margin-top: -100px;
}
</style>

四 flex 布局

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

五 grid 布局

<div id="box">
<div class="one"></div>
<div class="two">target item</div>
<div class="three"></div>
</div>
<style>
#box {
width: 300px;
height: 300px;
display: grid;
}
.two {
background: orange;
}
.one,
.three {
background: skyblue;
}
</style>

六 文本和图片垂直居中

/* line-height 等于高度 */
.father {
height: 100px;
line-hight: 100px;
}
/* 再添加 vertical-align: middle 居中图片*/
.father img {
vertical-align: middle;
}

七 table 居中

.father {
display: table;
}
.child {
display: table-cell;
vertical-align: center;
}