当父元素是行内元素时,是不需要子元素居中的。或者使用display:block属性把父元素变为块级元素,再做居中。
行内元素
(1)一行文字的垂直居中。设置行高等于父元素的高度,即可令文字垂直居中。
<style>
.parent{
height: 30px;
line-height:30px;
}
</style>
<div class="parent">
啦啦啦啦
</div>
(2)多行文字的垂直居中。
方法一:给父元素设置display:table-cell; vertical-align:middle。
<style>
.parent{
width: 100%;
height: 300px;
dispaly:table-cell;
vertical-align:middle;
}
</style>
<div class="parent">
啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦
</div>
注意:当父元素的高度不定时,单行文本使用这个方法也很有用。
方法二:将子元素变为块级元素,使用块级元素的垂直居中方法。
参考:https://blog.csdn.net/carpenterworm1874/article/details/79664675
块级元素:
块级元素的垂直居中主要分为两类:定高和不定高。
当块级元素定高时
方法一:position + 负margin
<style>
.parent{
position: relative;
width:100%;
height: 500px;
}
.child{
position:absolute;
top: 50%;
margin-top: -50px;
width: 100px;
height: 100px;
background: red;
}
</style>
<div class="parent">
<div class="child"></div>
</div>
当块级元素不定高时
方法一: position + margin auto
<style>
.parent{
position: relative;
width:100%;
height: 500px;
}
.child{
position:absolute;
top: 0;
bottom:0;
margin: auto;
width: 100px;
height: 100px;
background: red;
}
</style>
<div class="parent">
<div class="child"></div>
</div>
方法二:margin+transform
<style>
.parent{
position: relative;
width:100%;
height: 500px;
}
.child{
position:absolute;
top: 50%;
translateY(-50%);
width: 100px;
height: 100px;
background: red;
}
</style>
<div class="parent">
<div class="child"></div>
</div>
这个方法兼容性很好,是非常常用的方法。
方法三:table布局。
tabel单元格中的内容天然就是垂直居中的,我们可以把块级元素变为table单元格,实现居中。
<style>
.parent{
display:table-cell;
vertical-align:middle;
width:100%;
height: 500px;
}
.child{
width: 100px;
height: 100px;
background: red;
}
</style>
<div class="parent">
<div class="child"></div>
</div>
方法四:line-height
<style>
.parent{
width:100%;
height: 500px;
line-height:500px;
font-size:0;
}
.child{
display:inline-block;
vertical-align:middle;
width: 100px;
height: 100px;
font-size:12px;
background: red;
}
</style>
<div class="parent">
<div class="child"></div>
</div>
这种方法先使用display:inline-block让子元素拥有行内元素的特性,再使用父元素的line-height 等于height,再用vertical-align:middle;使得子元素可以垂直居中。font-size:0;的作用是消除垂直方向上的偏差。
注意:这种方法需要在子元素中将文字显示重置为想要的效果.
方法五:flex布局
<style>
.parent{
width:100%;
height: 500px;
display:flex;
align-items: center;
}
.child{
width: 100px;
height: 100px;
background: red;
}
</style>
<div class="parent">
<div class="child"></div>
</div>
flex布局是专为布局而生的,用起来非常方便,但要注意兼容性。目前在移动端已经完全可以使用flex了,PC端需要看自己业务的兼容性情况。
方法六:grid布局
参考文章:
https://blog.csdn.net/weixin_37580235/article/details/82317240