在明确宽高尺寸情况下,实现水平垂直居中方法:
1、使用固定定位
.div{
width: 300px;
height: 100px;
background:#fff;
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
2、使用相对定位与绝对定位
<div class="div1">
<div class="div2"></div>
</div>
.div1{
position: relative;
}
.div2{
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
width: 300px;
height: 100px;
}
在 未明确 高度尺寸情况下,实现水平垂直居中方法:
1、使用transform: translate
.div {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
margin: auto;
width: 300px;
}
2、使用弹性布局
<style>
.div1{
display: flex;
justify-content: center;
align-items: center;
margin: auto;
width: 300px;
height: 100%;
}
.div2{
background:#fff;
}
</style>
<div class="div1">
<div class="div2"></div>
</div>
最后,如果我的笔记对您有帮助,请给我一个赞~ 谢谢!