flex佈局中align-items 和align-content的區別
看了很多翻譯的技術文件,這一塊都講得模糊不清,看到stackoverflow上有人提問後的回答覺得十分清晰,特來分享,有不當之處歡迎指正。
align-items
The align-items property applies to all flex containers, and sets the
default alignment of the flex items along the cross axis of each flex
line.
align-items屬性適用於所有的flex容器,它是用來設定每個flex元素在側軸上的預設對齊方式。
還有一位回答者的回答也很好,如下
align-items has the same functionality as align-content but the difference is that it works to center every single-line container instead of centering the whole container.
align-items和align-content有相同的功能,不過不同點是它是用來讓每一個單行的容器居中而不是讓整個容器居中。
如下圖
align-content
The align-content property only applies to multi-line flex containers, and aligns the flex lines within the flex container when there is extra space in the cross-axis.
align-content屬性只適用於多行的flex容器,並且當側軸上有多餘空間使flex容器內的flex線對齊。
感覺這樣翻譯了之後還是略微有些抽象,不過有一個重點就是多行,
下面我們來寫一個小的例子。
<div class="child-1">
<div class="child-2">
</div>
<div class="child-2">
</div>
</div>
html結構如上。
如果child-1的width
100px
,child-2的width
設定為30px
,這樣child-2會排列在一排上,具體的css如下
<style type="text/css">
*{
margin:0px;
padding: 0px;
}
div{
border: 1px solid #0f0f0f;
}
.child-1{
margin: 30px auto;
display: flex;
width: 100px;
height: 60px;
justify-content: space-around;
align-content: center;
}
.child-2{
width: 30px;
height: 20px;
}
</style>
最終的結果如下圖
所以對於只有一行的flex元素,align-content是沒有效果的,如果.child-1
改用align-items:center;
則會達到預期的效果,如下圖
但如果變成多行容器
使用align-items
時效果如下
使用align-content
效果如下