第一种:
## .main{
width: 100%;
height: 100%;
}
.content{
width: 480px;
height: 380px;
line-height: 380px;
background-color: #ccc;
text-align: center;
position: absolute;
top: 50%;
left: 50%;
margin-top: -190px; /*height的一半*/
margin-left: -240px; /*width的一半*/
}
<div class="main">
<div class="content">我想要居中!!</div>
</div>
第二种:
body{
height: 100vh; /* 相对于视窗的高度, 视窗被均分为100单位的vh; */
}
.main{
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
}
.content{
width: 480px;
height: 380px;
background: #ccc;
display: flex;
align-items: center;
justify-content: center;
}
<div class="main">
<div class="content">我想要居中!!</div>
</div>
传统css水平垂直居中划重点:left:50%后需要margin-left:height/2,top同理;
flex水平垂直居中划重点:外层容器必须要有一个高度,如height:100vh;