div嵌套div水平垂直居中可以使用position定位來實現,這是最常用的方法。
<!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這四個屬性。
通常單獨使用left、right、top、bottom均無效,需要在使用絕對定位position樣式才能生效。
一般left和right在一個樣式是只能使用其一,不能left和right都設置,要么使用left就不使用right,要么使用right就不使用left,如果left和right均使用將會出現兼容問題,一個對象設置了靠左left多少距離,自然右邊距離自然就有了所以無需設置左邊。
相同道理,top和bottom對一個對象只能使用其一,不然會出現邏輯兼容問題。譬如一個人讓你往左走,一個人讓你往右走,同時發出往左往右走這個時候你也不好判斷往那邊走。
