前言
各位小伙伴在面试中总会遇到这么一道面试官常考的面试题,在开发中总会遇到这样的需求,那就是垂直水平居中的问题,那么如何实现呢?小编为此准备了几种实现方式~希望对大家有所帮助
1.绝对定位
- 子绝父相(子元素使用绝对定位,父元素使用相对定位)
- 根据盒子(box)宽高,用margin把自身移动负一半距离,以此来实现垂直水平居中的效果
// 接下来HTML都是这个部分
<div class="container">
<div class="box"></div>
</div>
.container {
width: 100%;
height: 100%;
position: relative;
}
.box {
position: absolute;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -50px;
width: 100px;
height: 100px;
background-color: #008c8c;
}
2. 绝对定位
- 子绝父相(子元素使用绝对定位,父元素使用相对定位)
- 用transform来移动盒子自身的宽高,以此来实现垂直水平居中的效果
.container {
width: 100%;
height: 100%;
position: relative;
}
.box {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 100px;
height: 100px;
background-color: #008c8c;
}
3.绝对定位
- 子绝父相(子元素使用绝对定位,父元素使用相对定位)
- 用margin:auto实现,以此来实现垂直水平居中的效果
.container {
width: 100%;
height: 100%;
position: relative;
}
.box {
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
margin: auto;
width: 100px;
height: 100px;
background-color: pink;
}
4.绝对定位
- 子绝父相(子元素使用绝对定位,父元素使用相对定位)
- 用css3新出的计算属性calc() 算,以此来实现垂直水平居中的效果
.container {
width: 100%;
height: 100%;
position: relative;
}
.box {
position: absolute;
top: calc(50% - 50px);
left: calc(50% - 50px);
width: 100px;
height: 100px;
background-color: #008c8c;
}
5.flex布局
- 将父容器设置为flex布局
- 并使用justify-content: center; align-items: center来实现居中,以此来实现垂直水平居中的效果
.container {
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
}
.box {
width: 100px;
height: 100px;
background-color: pink;
}
6.grid布局
- 将父容器设置为flex布局
- 并使用justify-content: center; align-items: center来实现居中,以此来实现垂直水平居中的效果
.container {
width: 100%;
height: 100%;
display: grid;
justify-content: center;
align-items: center;
}
.box {
width: 100px;
height: 100px;
background-color: #008c8c;
}
总结
- position + margin
- position + transform
- position + margin
- position + calc
- flex
- grid
本篇只讲了比较常用的几种实现垂直水平居中的方法,有什么纰漏或者不恰当的地方或者如果还有更好的实现方法,请各位大神在评论区赐教~