垂直居中方法总结
<style>
#box{
position: absolute;
margin: auto;
top:0px;
right: 0px;
bottom: 0px;
left: 0px;
width: 100%;
height: 30%;
background-color: red;
text-align: center;
}
</style>
<body>
<div id="box">
<h1>文字居中</h1>
</div>
</body>

第一种的好处是不用知道垂直居中的元素的高宽,但是必须设置元素的宽高!然后通过margin:auto;来达到效果。
<style>
#box{
position: absolute;
top:50%;
left:50%;
transform:translate3d(-50%,50%,0);
background-color: red;
text-align: center;
}
</style>
<body>
<div id="box">
<h1>文字居中</h1>
</div>
</body>

这种的好处是宽高不用定义!
<style>
.box{
display: flex;
height: 400px;
align-items:center;
justify-content:center;
background: #0099cc
}
h1{
display: flex;
align-items:center;
justify-content:center;
}
</style>
<body>
<div class="box">
<h1>实现元素水平居中</h1>
</div>
</body>

想要让那个元素居中,就在其父元素加 display:flex;justify-content:center;align-items:center;
按照原理,往body里设置这3个样式,就能按body垂直居中,但是没有,是因为body的默认高度为0px;在给个height:600px;就会有效果的!
<style>
#container{
position: absolute;
top:0px;
right: 0px;
bottom: 0px;
left: 0px;
display: flex;
justify-content:center;
align-items:center;
}
.box{
display: flex;
height: 400px;
align-items:center;
justify-content:center;
background: #0099cc
}
h1{
display: flex;
align-items:center;
justify-content:center;
}
</style>
<body>
<div id="container">
<div class="box">
<h1>实现元素水平居中</h1>
</div>
</div>
</body>

对于移动端,这是我常用的一种方法,这样屏幕的宽高就都有了!

浙公网安备 33010602011771号