概述
1.absolute + margin auto
<style>
.wrap {
position: relative;
width: 200px;
height: 200px;
border: 1px solid blueviolet;
}
.children {
margin:auto;
bottom: 0;
right: 0;
left: 0;
top: 0;
position: absolute;
width: 100px;
height: 100px;
background: beige;
}
</style>
<body>
<div class="wrap">
<div class="children">子元素</div>
</div>
</body>
2.absolute + 负margin
<style>
.wrap {
position: relative;
width: 200px;
height: 200px;
border: 1px solid blueviolet;
}
.children {
margin-left: -50px;
margin-top: -50px;
top: 50%;
left: 50%;
position: absolute;
width: 100px;
height: 100px;
background: beige;
}
</style>
<body>
<div class="wrap">
<div class="children">子元素</div>
</div>
</body>
3.absolute + calc
<style>
.wrap {
position: relative;
width: 200px;
height: 200px;
border: 1px solid blueviolet;
}
.children {
top:calc(50% - 50px);
left:calc(50% - 50px);
position: absolute;
width: 100px;
height: 100px;
background: beige;
}
</style>
<body>
<div class="wrap">
<div class="children">子元素</div>
</div>
</body>
4.absolute + transform
<style>
.wrap {
position: relative;
width: 200px;
height: 200px;
border: 1px solid blueviolet;
}
.children {
top:50%;
left:50%;
position: absolute;
transform: translate(-50%,-50%);
width: 100px;
height: 100px;
background: beige;
}
</style>
<body>
<div class="wrap">
<div class="children">子元素</div>
</div>
</body>
5.flex
<style>
.wrap {
display: flex;
justify-content: center;
align-items: center;
width: 200px;
height: 200px;
border: 1px solid blueviolet;
}
.children {
width: 100px;
height: 100px;
background: beige;
}
</style>
<body>
<div class="wrap">
<div class="children">子元素</div>
</div>
</body>
6.css-table
<style>
.wrap {
display: table-cell;
text-align: center;
vertical-align: middle;
width: 200px;
height: 200px;
border: 1px solid blueviolet;
}
.children {
display: inline-block;
width: 100px;
height: 100px;
background: beige;
}
</style>
<body>
<div class="wrap">
<div class="children">子元素</div>
</div>
</body>
总结:
这些是我经常使用的,如有新的方法,欢迎交流
对比优缺点:
1.pc端宽高固定建议使用:absolute + 负margin;
2.pc端无宽高:css-table;
3.无兼容性:flex;
4.移动端建议使用flex,真的超级好用
最后
以上就是整齐老虎为你收集整理的css实现垂直居中(面试的时候面试官经常会问的)的全部内容,希望文章能够帮你解决css实现垂直居中(面试的时候面试官经常会问的)所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复