在平時,我們經常會碰到讓一個div框針對某個模塊上下左右都居中(水平垂直居中),其實針對這種情況,我們有多種方法實現。
方法一:
絕對定位方法:不確定當前div的寬度和高度,采用 transform: translate(-50%,-50%); 當前div的父級添加相對定位(position: relative;)
圖片展示:

代碼如下:
div{
background:red;
position: absolute;
left:50%;
top:50%;
transform: translate(-50%, -50%);
}
方法二:
絕對定位方法:確定了當前div的寬度,margin值為當前div寬度一半的負值
圖片展示: 如方法一的圖片展示
代碼如下:
div{
width:600px;
height: 600px;
background:red;
position: absolute;
left:50%;
top:50%;
margin-left:-300px;
margin-top:-300px;
}
方法三:
絕對定位方法:絕對定位下top left right bottom 都設置0
圖片展示: 如方法一的圖片展示
代碼如下:
<!--html-->
<div class="child">我是子級</div>
/**css**/
div.child{
width: 600px;
height: 600px;
background: red;
position:absolute;
left:0;
top: 0;
bottom: 0;
right: 0;
margin: auto;
}
方法四:
flex布局方法:當前div的父級添加flex css樣式
展示圖如下:

代碼如下:
<!--html-->
<div class="box">
<div class="child">child</div>
</div>
/**css**/
.box{
height:800px;
-webkit-display:flex;
display:flex;
-webkit-align-items:center;
align-items:center;
-webkit-justify-content:center;
justify-content:center;
border:1px solid #ccc;
}
div.child{
width:600px;
height:600px;
background-color:red;
}
方法五:
table-cell實現水平垂直居中: table-cell middle center組合使用
展示圖如下:

代碼如下:
<!--html-->
<div class="table-cell">
<p>我愛你</p>
</div>
/**css**/
.table-cell {
display: table-cell;
vertical-align: middle;
text-align: center;
width: 240px;
height: 180px;
border:1px solid #666;
}
方法六:
絕對定位:calc() 函數動態計算實現水平垂直居中
展示圖如下:

代碼如下:
<!--html-->
<div class="calc">
<div class="child">calc</div>
</div>
/**css**/
.calc{
position: relative;
border: 1px solid #ccc;
width: 400px;
height: 160px;
}
.calc .child{
position: absolute;
width: 200px;
height: 50px;
left:-webkit-calc((400px - 200px)/2);
top:-webkit-calc((160px - 50px)/2);
left:-moz-calc((400px - 200px)/2);
top:-moz-calc((160px - 50px)/2);
left:calc((400px - 200px)/2);
top:calc((160px - 50px)/2);
}
