持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第21天,点击查看活动详情
在面试时,经常会遇到一个很基础的问题:关于水平垂直居中,也分两种情况,一种是定宽高的,一种是不定宽高的。
以下边demo为例,以下方法均使用此例子,目的让needMid元素垂直水平居中
<div class="parent">
<div class="needMid">000
</div>
<div>
定宽高的话其实比较简单,可以根据元素的宽高,调整左右的距离即可实现。以下三种方式可提供参考
absoulte+margin auto
通过设置父元素position:relative为相对定位,设置需要居中的子元素position:absolute,再设置元素距离各个方向均为0,margin设为auto,这样即可实现水平垂直居中
代码如下:
.parent{
position: relative;
width: 100px;
height: 100px;
}
.needMid{
position: absolute;
width: 20px;
height: 20px;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
缺点:不需要知道子元素的宽高,但子元素需要定宽高
优点:兼容性较好
absoulte+负margin
通过设置父元素position:relative为相对定位,设置需要居中的子元素position:absolute,接着设置元素距顶部和左部50%,再设置负margin是高度或宽度的一半
代码如下:
.parent{
position: relative;
width: 100px;
height: 100px;
}
.needMid{
position: absolute;
width: 20px;
height: 20px;
top: 50%;
left: 50%;
margin-left:-10px ;
margin-right:-10px ;
}
缺点:需要知道子元素的宽高
优点:兼容性较好,较好理解
absoulte+calc
通过设置父元素position:relative为相对定位,设置需要居中的子元素position:absolute,接着设置top/left的百分比是基于元素的左上角,那么在减去宽度/高度的一半
.parent{
position: relative;
width: 100px;
height: 100px;
}
.needMid{
position: absolute;
width: 20px;
height: 20px;
top: calc(50% - 10px);
left: calc(50% - 10px);
}
缺点:兼容性依赖calc的兼容性,需要知道子元素的宽高
优点:好理解
以上就是需要限制元素固定宽高的三种设置垂直居中的方式,下文为大家总结不需要子元素固定宽高的常用方法。