0.前言
在編寫下圖類似的HTML時,我最初使用的float,發現浮動的寫法很不方便,后面經百度改用display:flex進行布局,並對這一CSS屬性產生了濃厚的興趣。
通過幾行代碼輕松解決了左右對齊顯示,並且意外發現通過 align-items: center 還可以實現上下對齊居中
我正在使用 styled-components 去實現前端效果,所以代碼分為樣式部分style.js和頁面部分index.js
style.js:
1 export const Legend = styled.div` 2 width: 100%; 3 display: flex; 4 display: -webkit-flex; 5 margin:10px 0px; 6 7 .left { 8 text-align: left; 9 font-size: 16px; 10 11 img{ 12 margin-right: 5px; 13 } 14 } 15 16 .right { 17 flex: 1; 18 display: flex; 19 display: -webkit-flex; 20 align-items: center; 21 justify-content: flex-end; 22 } 23 `;
index.js:
1 <Divider>圖例</Divider> 2 { 3 this.state.thematicLayers.length>0?( 4 this.state.thematicLayers.map(item => { 5 return ( 6 <Legend> 7 <div className='left'> 8 <img src={item.tPic} />{item.tName} 9 </div> 10 <div className='right'> 11 <Switch /> 12 </div> 13 </Legend> 14 ) 15 }) 16 ):( 17 <div>暫無圖層數據</div> 18 ) 19 }
下面進入正題,Flex是彈性布局的意思,可以為任意元素指定為Flex布局
1 .box{ 2 display: flex; 3 display: -webkit-flex; /*兼容Safari(ios)*/ 4 }
1.flex-direction 屬性
主要參數: row | row-reverse | column | column-reverse
主要代碼:
1 export const FlexBox = styled.div` 2 width: 1000px; 3 margin: 0 auto; 4 background: #7B68EE 5 display: flex; 6 display: -webkit-flex; 7 flex-direction: row | row-reverse | column | column-reverse; 8 `; 9 10 export const FlexBoxItem = styled.div` 11 background: #FFD700; 12 width: ${props => props.width?props.width:'100px'}; 13 height: ${props => props.width?props.width:'100px'}; 14 margin: 10px; 15 `;
row
(默認)水平方向,起點在左端
row-reverse
水平方向,起點在右端
column
垂直方向,起點在上邊沿

2.flex-warp 屬性
主要參數:nowrap | wrap | wrap-reverse
主要代碼:
1 export const FlexBox = styled.div` 2 width: 500px; 3 margin: 0 auto; 4 margin-top: 100px; 5 background: #7B68EE 6 display: flex; 7 display: -webkit-flex; 8 flex-warp: nowrap | wrap | wrap-reverse; 9 `; 10 11 export const FlexBoxItem = styled.div` 12 background: #FFD700; 13 width: ${props => props.width?props.width:'100px'}; 14 height: ${props => props.width?props.width:'100px'}; 15 margin: 10px; 16 `;
nowrap
不換行,會擠在一行,之前設定的寬度會失效,margin仍有效,圖一為三個,圖二為多個


wrap
換行,且第一行在上方
換行,且第一行在下方

3.flex-flow屬性


4.justify-content屬性
主要參數: flex-start | flex-end | center | left | right | space-between | space-around | space-evenly | stretch | safe | unsafe | baseline | first baseline | last baseline

flex-end
終點對齊,注意這邊和上面的flex-direction:row-reverse不同,他並沒有調整子元素的順序
center
居中
space-around


5.align-items 屬性
主要參數: flex-start | flex-end | center | baseline | stretch

flex-end
靠下對齊
center
垂直居中(賊好用,我不管我要標紅)
baseline
第一行文字對齊,這個可以用來做效果
大致就是以上這些,連代碼帶查資料寫了2個多小時,腦殼疼