div中的div如何居中


<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title></title>
        <style type="text/css">
        </style>
    </head>
    <body>
        <div class="father">
            <div class="son">son</div>
        </div>
    </body>
</html>

方法一(使用絕對布局): 這種方式的弊端是:必須要知道這個容器的長寬,因為在子元素中的    margin-top:-100px;    margin-left:-100px; 這兩個樣式分別是子元素長、寬的一半。

.father {
  width: 500px;
  height: 500px;
  position: relative;
  background-color: red;
}
 
.son {
  width: 200px;
  height: 200px;
  position: absolute;
  top: 50%;
  left: 50%;
  margin-top: -100px;
  margin-left: -100px;
  background-color: black;
}

方法二:仍然是絕對布局,讓left和top都是50%,這在水平方向上讓div的最左與屏幕的最左相距50%,垂直方向上一樣,所以再用transform向左(上)平移它自己寬度(高度)的50%,也就達到居中效果了,效果圖和上方相同。//這種方式很好的避免了方式一的弊端,不需要知道自己的長寬,一樣可以定位到中間。

.father{
  width: 1000px;
  height: 600px;
  position: relative;
  background-color: red;
}
.son {
  background-color: #fff;
  width: 300px;
  height: 300px;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}

方法三(使用彈性布局flex)://這種方式比較通用:這樣給父元素設置了三個樣式display:flex;(彈性布局)    justify-content:center;(內容水平居中)   align-items:center; (內容垂直居中) 就可以達到水平、垂直居中的效果。

.father {
  width: 500px;
  height: 500px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: red;
}
.son {
  width: 200px;
  height: 200px;
  background-color: black;
} 

方法四(使用絕對布局)://使用這種方式的要領是:子絕父相,且子元素要設置以下的樣式position:absolute; top:0; right:0; bottom:0; left:0; margin:auto; 就可以達到居中效果。

.father {
  width: 500px;
  height: 500px;
  position: relative;
  background-color: red;
}
 
.son {
  width: 200px;
  height: 200px;
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  margin: auto;
  background-color: black;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM