flex布局是一種很方便的布局,不用自己設置同行的div的高度相等,它們即可高度相等,并且可以方便的實現柵格系統等。下面是幾種常見的布局,看flex如何實現:
兩列等高布局:
左邊固定寬度,右邊占據剩余寬度:
<style>
*{
margin: 0;
padding:0;
}
.grid{
display: flex;
border: 1px solid #ccc;
}
.gridCell1{
background-color: #449fdb;
flex-basis: 100px;
}
.gridCell2{
background-color: #3355D0;
flex-basis:calc(100% - 100px);
}
</style>
<body>
<div class="grid">
<div class="gridCell1"><p>JS中沒有塊作用域的概念,所以下列的代碼中的i可以在全局環境中訪問,但這樣會有一個弊端:污染了全局環境,因為在大型工程中,有可能會導致變量沖突。</p></div>
<div class="gridCell2"><h1>標題</h1></div>
</div>
</body>
實現效果:
Paste_Image.png
可以看到上述代碼實現了一個左邊固定寬度,右邊占據剩余寬度的布局,并且高度相等。
原理:設置父容器為flex,子元素中左邊設置flex-basis屬性寬度為固定寬度,另外一個子元素的flex-basis屬性設置為100%減去這個固定寬度即可。
柵格系統:
在Bootstrap中可以很方便的使用柵格系統引入各個div的寬度劃分,如果不使用柵格系統,利用flex也是很容易實現的。
<style>
*{
margin: 0;
padding:0;
}
.grid{
display: flex;
border: 1px solid #ccc;
}
.gridCell1{
background-color: #449fdb;
flex: 1;
}
.gridCell2{
background-color: #3355D0;
flex: 4;
}
.gridCell3{
background-color: #b6d0ba;
flex: 1;
}
.gridCell4{
background-color: #d064b9;
flex: 1;
}
</style>
<body>
<div class="grid">
<div class="gridCell1"><p>JS中沒有塊作用域的概念,所以下列的代碼中的i可以在全局環境中訪問,但這樣會有一個弊端:污染了全局環境,因為在大型工程中,有可能會導致變量沖突。</p></div>
<div class="gridCell2"><p>文字1</p></div>
<div class="gridCell3"><p>文字2</p></div>
<div class="gridCell4"><p>文字3</p></div>
</div>
</body>
效果圖:
Paste_Image.png
如上,flex屬性為flex-grow flex-shrink flex-basis的簡寫屬性,當只有一個非負整數時,表示flex-grow的值,另外兩個值為 1和0%;flex-grow是項目的放大比例,所以上述四個div的寬度以1:4:1:1的形式呈現。
另一種情況:flex屬性為百分比的情況
<style>
*{
margin: 0;
padding:0;
}
.grid{
display: flex;
border: 1px solid #ccc;
}
.gridCell1{
background-color: #449fdb;
flex: 10%;
}
.gridCell2{
background-color: #3355D0;
flex: 40%;
}
.gridCell3{
background-color: #b6d0ba;
flex: 10%;
}
.gridCell4{
background-color: #d064b9;
flex: 40%;
}
</style>
<body>
<div class="grid">
<div class="gridCell1"><p>JS中沒有塊作用域的概念,所以下列的代碼中的i可以在全局環境中訪問,但這樣會有一個弊端:污染了全局環境,因為在大型工程中,有可能會導致變量沖突。</p></div>
<div class="gridCell2"><p>文字1</p></div>
<div class="gridCell3"><p>文字2</p></div>
<div class="gridCell4"><p>文字3</p></div>
</div>
</body>
效果圖:
Paste_Image.png
當flex屬性只有一個百分數時,表示的是flex-basis,其他的兩個值flex-grow和flex-shrink均為0.
圣杯布局:
Paste_Image.png
<style>
*{
margin: 0;
padding:0;
}
body{
display: flex;
flex-direction: column;
}
.header,.footer{
flex: 1;
background-color: #8591f7;
}
.container{
flex:1;
display: flex;
}
.left{
flex-basis:100px;
background-color: #449fdb;
}
.right{
flex-basis: 100px;
background-color: #3355D0;
}
.main{
flex-basis: calc(100% - 200px);
background-color: #6f7178;
}
</style>
<body>
<div class="header"><h1>標題</h1></div>
<div class="container">
<div class="left"><p>JS中沒有塊作用域的概念,所以下列的代碼中的i可以在全局環境中訪問,但這樣會有一個弊端:污染了全局環境,因為在大型工程中,有可能會導致變量沖突。</p></div>
<div class="main"><p>文字1</p></div>
<div class="right"><p>文字2</p></div>
</div>
<div class="footer"><p>頁腳</p></div>
</body>
該布局需要設置兩個flex,一個垂直方向,一個水平方向,垂直方向的容器為body,水平方向的容器為container。垂直方向的三個子元素分別設置flex屬性為1,水平方向的三個子元素分別各自設置flex-basis。