第一種

div {
position: absolute; /* 相對定位或絕對定位均可 */
width:500px;
height:300px;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: pink;
}

-----------------------------------------------------------------------------

第二種

利用 flex 佈局
#box{
display: flex;
display: -webkit-flex;
border: 1px solid #0000FF;
height: 200px;
align-items:center;
justify-content:center;
}
.item{
width: 50px;
height: 40px;
border: 1px solid #00C1B3;
text-align: center;
vertical-align: middle;
}
<div id="box">
<div class="item">1</div>
</div>

-----------------------------------------------------------------------------

第三種

.box{
width:300px;
height:300px;
background: red;
display: table-cell;
vertical-align: middle;
text-align: center;
}
<div class="box">
<div>垂直居中</div>
</div>

-----------------------------------------------------------------------------

第四種

絕對定位(或者relative和absolute相互作用)

.box{
width: 50%;
height: 50%;
background: #000;
overflow: auto;
margin: auto;
position: absolute;
top: 0; left: 0; bottom: 0; right: 0;
}
<div class="box"></div>

推薦閱讀:

相關文章