前言
上一篇flex布局筆記中對flex的相關布局語法有所了解,這里用它來實現幾個常見的場景:
幾個橫排元素在豎直方向上居中
display: flex;
flex-direction: row;//橫向排列
align-items: center;//垂直方向上居中
在母控件的正中:相當于android中的RelativeLayout的centerInParent=true.
display: flex;
flex-direction: row;//橫向排列
justify-content: center;//水平居中
align-items: center;//垂直方向上居中
自定義modal的一個標題欄,帶圖標的標題居中,右邊有關閉按鈕
1.png
繞的一個坑: 中間的用div包裹,flex布局可實現centerInParent效果,右邊的用position: absolute;right: 0.75rem,可以實現關閉按鈕在右邊,但是脫離的文檔流,居中不好弄.
能不能不脫離flex的文檔流?
2.png
可以的,左邊加一個空的div,就可以對稱了,用flex布局的justify-content: space-between,就能均勻排列了.
<div style="display: flex;flex-direction: row;justify-content: space-between;align-items: center;
align-content: center;background-color: #0d88c1;padding-left: 0.75rem;padding-right: 0.75rem">
<div></div>
<div style="display: flex;flex-direction: row;justify-content: center;align-items: center;background-color: #1f9d85">
<div style="font-size: 2rem">圖片</div>
<div >文字</div>
</div>
<div style="background-color: red;">x</div>
</div>
同理,利用justify-content: space-between + align-items: center 可以實現右邊垂直居中的效果:
把左邊的兩個元素用div包裹,然后和右邊的元素作為flex布局的兩個item,用space-between撐到兩邊.
3.png
常見的tab導航欄的實現
4.png
6.png
.tab-container{
display: flex;
flex-direction: row;//橫向排列
flex-wrap: nowrap;//不換行
overflow-x: scroll;//橫向放不下時允許滾動
justify-content:space-around;//各item之間被間隔包裹
align-items: center;//垂直方向上居中
}
/*tab欄的條目數,自動均分*/
.tab-items{
flex: 1 0 200rpx;//本身大小200rpx,可以擴張(1:比如只有兩個tab時,平分width),不許壓縮(0)
text-align: center;
padding-bottom: 25rpx;
padding-top: 25rpx;
font-size: 30rpx;
color: #333333;
}
布局練習:
1.item布局
5.png