問題:怎樣實現(xiàn)div元素居中(垂直、水平)?
<body>
<div id="father">
<div id="child">
讓我居中呀!
</div>
</div>
</body>
方法1:絕對定位法(transform屬性)
使用css3的transform設置元素進行水平垂直居中,不需要知道元素的寬、高
用絕對定位來實現(xiàn)的垂直居中,取決與元素的寬度和高度,可以用下面這兩個公式來計算元素的左邊距和上邊距:
元素的寬度/2 = 負左邊距
元素的高度/2 = 負上邊距
#father{
//假設主框為600*300
position: relative; /*很重要*/
width: 600px;
height: 300px;
background-color: blue:
}
#child{
position: absolute; /*很重要*/
/*子元素左上角定位到父級元素的正中間*/
top: 50%;
left: 50%;
/*子元素相對于自身左移上移到中間,實現(xiàn)居中定位*/
transform: translate(-50%,-50%);
background-color: lawngreen;
}
注意點:
(1)上述父級元素和子元素均采用絕對定位 position:absolute; 效果圖如下:
(父元素也可以采用 relative)
但是:如果子元素采用相對定位:position: relative; 那只能實現(xiàn)垂直居中,效果如下:
(父元素沒有定位時,子元素采用相對定位)
(2)上述方法利用了CSS3中的 transform:translate(x,y) 屬性,這是子元素相對于自身的定位實現(xiàn)的x軸和y軸的偏移,如果子元素沒有設置寬和高值的話可以用這個方法實現(xiàn)(做自適應頁面的時候用到),如果已知子元素的寬和高,可以用下述方法實現(xiàn)。
方法2:定位法(相對位置)
利用position生成絕對定位的元素進行水平垂直居中,該方法需要知道元素的寬、高
<style>
#father{
position:relative;
width:600px;
height:300px;
background-color:deepskyblue;
border: 2px red dashed;
}
#child{
position: absolute;
width:200px;
height:100px;
top: 50%;
left: 50%;
/*transform: translate(-50%,-50%);*/
margin-left:-100px;
margin-top:-50px;
background-color: lawngreen;
/*內(nèi)容居中*/
text-align: center;
line-height:100px; /*行間距和div寬度相同*/
}
</style>
效果如下:
方法3:定位法 margin:auto
使用position生成絕對定位與margin:auto結(jié)合讓元素進行水平垂直居中,改方法需要設置元素的寬、高
<style>
#father{
position:relative;
width:600px;
height:300px;
background-color:deepskyblue;
border: 2px red dashed;
}
#child{
position: absolute;
width : 200px;
height : 100px;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
background-color: lawngreen;
}
</style>
僅實現(xiàn)水平居中(子元素):margin:0 auto; (當子元素position為非默認及relative時,這種設置會失效)
僅實現(xiàn)垂直居中(子元素):margin:auto 0;
上述文字沒有實現(xiàn)居中,可參考方法2中的居中,但是要注意:如<p>等標簽中內(nèi)的文字內(nèi)容水平居中:使用{text-align:center}。垂直居中設置該元素的行高等于元素的高。
4. display:table-cell 實現(xiàn)法
display:table-cell 主要針對多行文字內(nèi)容的垂直居中對齊。
通過display轉(zhuǎn)化成為表格的形式,再采用垂直居中的方法得到需要的結(jié)果
display:table 此元素會作為塊級表格來顯示(類似 <table>),表格前后帶有換行符。
display:table-cell 此元素會作為一個表格單元格顯示(類似 <td> 和 <th>)
div {
display: table-cell;
width: 200px;
height: 200px;
text-align: center;
vertical-align: middle;
border: 1px solid #F00;
}
本文章來源于https://blog.csdn.net/chenjuan1993/article/details/82628930