让元素水平垂直居中的几种方式
平时我们做项目的时候很多情况会遇到让元素水平垂直居中的场景,可能场景不同,所以需要用不同的方式,下里面是可以实现的6种方式和他们的使用场景。
列如有个设定好的div,下面是他的样式

定位的话分为3种也可以说是三种情况,都是依赖于定位实现的。
1.定位
(1) 缺点:需要具体宽高的情况下使用
.box{
position: absolute;
top: 50%;
left: 50%;
margin-top: -100px;
margin-left: -100px;
}
(2)不需要知道具体宽高的情况下,但是必须得有宽高
.box{
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
(3) 也不需要有宽高,但是必须有内容撑开就好,缺点:css3的兼容性问题,不考虑兼容的话不错的方案
.box{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
2.弹性布局
移动端用的较多,方便,但是也会有兼容性问题
body{
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
//这里是body,给其父盒子设定就好利用弹性布局居中
3.使用js实现
有时候我们需要在js中完成
<script>
let box=document.getElementById('box')
let html=document.documentElement
winw=html.clientWidth
winh=html.clientHeight
boxw=box.offsetWidth
boxh=box.offsetHeight
box.style.position='absolute'
box.style.left=(winw-boxw)/+'px'
box.style.top=(winh-boxh)/+'px'
</script>
4.使用文本居中的方式
这种水平垂直居中的方式不常用,需要把元素转换为行内块元素,给父盒子写css
body{
height: 100vh;
display:table-cell;
vertical-align: middle;
text-align: center;
}
.box{
display: inline-block;
}
335




被折叠的 条评论
为什么被折叠?



