flex佈局shi'xian

1:web頁面佈局(topbar + main + footbar)

html代碼:css

<div class="container">
     <header>header...</header>
     <main>內容</main>
     <footer>footer...</footer>
   </div>

css代碼html

header{
  height:100px;
  background:#ccc;
}
footer{
  height:100px;
  background:#ccc;
}
.container{
  display:flex;
  flex-direction:column;
  height:100vh;
}
main{
  flex-grow:1;
}

1:使用flex-direction使總體佈局從上向下佈局web

2:flex-grow:1使得main自動填充剩餘的空間ide

2:每行的項目數固定並自動換行的列表項

css代碼佈局

ul{
  display:flex;
  flex-wrap:wrap;
}
li{
  list-style:none;
  flex:0 0 25%;
  background:#ddd;
  height:100px;
  border:1px solid red;
}

1:flex:0 0 25%,至關於flex-basis:25%,使得每個列表項的寬度佔外層容器(本例中的ul元素)的25%,所以每行最多可以排開四個列表項。post

2:flex-wrap:wrap,使得每行填滿時會自動換行flex

3:實現自動劃分多餘空間的列表項

css代碼spa

ul{
  display:flex;
  flex-wrap:wrap;
  justify-content:space-between;
  border:1px solid black;
}
li{
  list-style:none;
  width:120px;
  background:#ddd;
  height:100px;
  border:1px solid red;
}

 

1:justify-content:space-between;使主軸方向的多餘空間平均分配在兩兩item之間code

4:平均分配空間的柵格佈局

html代碼htm

<div class="row">
         <div class="column">column1</div>
         <div  class="column">colum22</div>
         <div  class="column">colum322</div>
</div>

css代碼

.row{
  display:flex;
  flex-wrap:wrap;
  border:1px solid black;
}
.column{
  list-style:none;
  background:#ddd;
  flex:1;
  height:100px;
  border:1px solid red;
}
flex:1 這裏針對item應用了flex:1,至關於flex:1 1 0%,而之因此無論各個column元素內容的寬度爲多大,都能均分到相等的空間,正式由於至關於在設置了flex-grow:1使得剩餘空間按相等比例自動分配的同時又設置了flex-basis:0%,才使得整個空間都平均分配了(更詳細的關於[flex]縮寫屬性,請戳 從新認識flex縮寫屬性—[flex])。

5:聖盃佈局

html代碼

<div class="container">
       <main>main</main>
       <aside>aside</aside>
       
       <nav>nav</nav>
</div>

css代碼

.container{
  display:flex;
  height:100vh;
}
aside{
  width:50px;
  background:#ccc;
}
main{
  flex-grow:1;
  background:#def;
}
nav{
  width:80px;
  background:#ccc;
  order:-1;
}
  1. 對main用flex-grow:1,使得中間主元素空間自動擴充
  2. 對nav應用order:-1,使得order處於最左側(html中main寫在了最前,以利於優先加載主內容區)

6:元素水平垂直居中

html代碼

 <div class="container">
       <div class="inner">我是中間的內容</div>
 </div>

css代碼

.container{
  height:300px;
  width:300px;
  border:1px solid red;
  display:flex;
  justify-content:center;
  align-items:center;
}

.inner{
  border:1px solid black;
}
  1. justify-content:center;使item元素水平居中
  2. align-items:center;使item元素垂直居中

  這麼多場景都難不倒flex有木有,果真名不虛傳~(  想更詳細的瞭解flex相關屬性的話,請戳flex入門—瞭解這些flex屬性~)

相關文章
相關標籤/搜索