css flex經典三大布局:垂直居中,兩列等高,自適應寬


用flex實現css里的三大經典布局,不需要額外很多代碼。

1,垂直居中 :子元素在父元素中,水平垂直居中。justify-content:center設置水平方向居中,align-center設置垂直方向居中。
<div id="parent">
    <div id="child"></div>
  </div>
#parent {
/* align-content和align-items必須配合使用 */
      display: flex;
      justify-content: center;
      align-content: center;
      align-items: center;
      width: 300px;
      height: 300px;
      outline: solid 1px;
    }
    #child {
      width: 100px;
      height: 100px;
      outline: solid 1px;
    }

 

2,二列等高:父元素里有二個子元素,一個設置高度,另一個需要和它高度一致。
 <div id="parent">
    <div id="child" style="height: 300px;"></div>
    <div id="child"></div>
  </div>
#parent {
      display: flex;
      justify-content: center;
      align-content: center;
/*  stretch讓盒子內的每個元素的高度都等於行高 */
      align-items: stretch; 
      width: 300px;
    }
    #child {
      width: 100px;
      outline: solid 1px;
    }

 

3,自適應寬:父元素里有二個子元素,一個設置寬度,另外一個占據剩余的寬度。
<div id="parent">
    <div id="child1"></div>
    <div id="child2"></div>
  </div>
#parent {
      display: flex;
      width: 300px;
      height: 200px;
      background-color: pink;
    }
    #child1 {
      flex: 1;
      /* 即使設置100px寬,還是會占據剩余的所有寬度 */
      width: 100px;  
      background-color: lightblue;
    }
    #child2 {
      width: 100px;
      outline: solid 1px;
    }

 


免責聲明!

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



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