想要實(shí)現(xiàn)頁(yè)面中垂直水平居中:
使用flex布局:
.test {
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
height: 400px;
}
<div class="test">
<p>dddd</p>
<p>kkkkkk</p>
<h3>llllll</h3>
</div>
flex-direction屬性決定主軸的方向(即項(xiàng)目的排列方向)。
默認(rèn)是row硼莽,表示items水平排列
因此要使項(xiàng)目垂直排列需設(shè)置flex-direction: column;
此時(shí)justify-content: center;表示垂直方向上的居中
align-items: center;表示水平方向上的居中
垂直方向上的居中父元素需要有高度
flex常見屬性
1.justify-content
justify-content屬性定義了項(xiàng)目在主軸上的對(duì)齊方式。
.box {
justify-content: flex-start | flex-end | center | space-between | space-around;
}
它可能取5個(gè)值猜极,具體對(duì)齊方式與軸的方向有關(guān)缨叫。下面假設(shè)主軸為從左到右。
- flex-start(默認(rèn)值):左對(duì)齊
- flex-end:右對(duì)齊
- center: 居中
- space-between:兩端對(duì)齊剪勿,項(xiàng)目之間的間隔都相等贸诚。
- space-around:每個(gè)項(xiàng)目?jī)蓚?cè)的間隔相等。所以厕吉,項(xiàng)目之間的間隔比項(xiàng)目與邊框的間隔大一倍酱固。
2.align-items
align-items屬性定義了項(xiàng)目在交叉軸上的對(duì)齊方式。
注意:
使用flex會(huì)使子元素的float 头朱、 clear 和 vertical-align 屬性失效运悲。因此,使用了flex布局项钮,就不要用浮動(dòng)
常見布局
1.元素a在最左班眯,元素b在最右
想要實(shí)現(xiàn)float布局能實(shí)現(xiàn)的樣式,例如元素a在最左烁巫,元素b在最右
可以
display: flex;
justify-content: space-between;
2.元素均分一行
實(shí)現(xiàn)元素均分一行:
display: flex;
justify-content: space-between;
使用space-between鳖敷、space-around看具體場(chǎng)景
3.元素a在中間,元素b在最右
這種情況不太推薦用flex布局程拭,如果非要用flex:
在最左側(cè)加一個(gè)區(qū)塊定踱,形成結(jié)構(gòu) 與箭頭等寬塊---標(biāo)題----箭頭, 這樣可以解決問(wèn)題恃鞋,有點(diǎn)不太優(yōu)雅崖媚。
推薦使用:
采用絕對(duì)定位:箭頭使用絕對(duì)定位亦歉,標(biāo)題水平居中即可(text-align:center)