div嵌套div水平垂直居中能夠使用position定位來實現,這是最經常使用的方法。css
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style type="text/css"> .div1 { width:800px; height:500px; border:2px solid #000; position:relative; } .div2 { width:200px; height:200px; margin: auto; position: absolute; top: 0; left: 0; bottom: 0; right: 0; background-color: red; } </style> </head> <body> <div class="div1"> <div class="div2"></div> </div> </body> </html>
須要注意的是 left right top bottom這四個屬性。html
一般單獨使用left、right、top、bottom均無效,須要在使用絕對定位position樣式才能生效。htm
通常left和right在一個樣式是隻能使用其一,不能left和right都設置,要麼使用left就不使用right,要麼使用right就不使用left,若是left和right均使用將會出現兼容問題,一個對象設置了靠左left多少距離,天然右邊距離天然就有了因此無需設置左邊。對象
相同道理,top和bottom對一個對象只能使用其一,否則會出現邏輯兼容問題。譬如一我的讓你往左走,一我的讓你往右走,同時發出往左往右走這個時候你也很差判斷往那邊走。blog