鍍金池/ 問答/數(shù)據(jù)庫  HTML/ CSS3 flex 布局,我用技巧生成正方形,但是里面布局的失敗后為什么布局中呢

CSS3 flex 布局,我用技巧生成正方形,但是里面布局的失敗后為什么布局中呢?

我是用flex布局,通過技巧生成正方形,然后現(xiàn)在里面對(duì)紅方塊進(jìn)行居中,但是位置異常,直接飄到上面去了,原因是什么呢?
`
<!DOCTYPE html>
<html lang="en">
<head>

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
    #app{
        margin: auto auto;
        width : 600px;
        height : 800px;
        background-color : #cccccc;
    }
    .d1{
        width: 100%;
        height: 0;
        padding-bottom: 100%;
        background-color: #656565
    
    }
    .d2{
        width: 100%;
        height: 100%;
        display: flex;
        flex-direction: column;
        justify-content: center;
        box-sizing: border-box;
        position: relative
    }
    .clo{
        position: absolute;
        width: 200px;
        height:200px;
        background: red;
    
    }

</style>

</head>
<body>

<div id="app">
    <div class="d1">
        <div class="d2">
            <div class="clo"></div>
        </div>
    </div>
</div>

</body>
</html>
`
圖片描述

據(jù)我觀察,圖片自動(dòng)和 .d1的中間位置對(duì)齊了,但是我明明設(shè)置了 box-sizing=border-box啊,他為什么還是會(huì)跑出這個(gè)盒子?
謝謝大神~~~~

回答
編輯回答
還吻

你看到的紅色正方形被瀏覽器窗口截?cái)?/strong>了!你把#app的margin-top調(diào)的高一些再看,比如200px,會(huì)是如下效果

clipboard.png

有沒有發(fā)現(xiàn)什么?紅色正方形的中心卡在了容器邊緣,正好被平分。接下來我們解釋為什么會(huì)這樣。
  1. height:100%這類屬性是相對(duì)父元素的, d1高度為0,d2雖然設(shè)定高度100%,結(jié)果也是0.
  2. flex容器中的元素,即使是絕對(duì)定位,在沒有設(shè)定“top,left,right,bottom"等會(huì)變化位置的屬性前,受flex指定布局的擺布。
  3. 紅色塊 在高度為 0的 flex容器d2中,被設(shè)定為垂直居中,它現(xiàn)在完美的將自己的中心卡在了d2所在的水平線上。

本例中若想實(shí)現(xiàn)預(yù)期效果,稍作調(diào)整即可

  1. d1增加屬性

      box-sizing: border-box;
      position: relative;
  2. d2將position屬性值改為absolute
2018年3月8日 21:24