最近在研究flex布局,容器中有兩個屬性,是用來定義crossAxis測軸排列方式的。一開始接觸align-items還可以理解感覺不難,后來看到align-content就感覺有點混淆了,特開一篇博客記錄一下我的學習過程。先來看看兩個屬性的基本用法和定義,這里摘抄於螢火蟲塔莉上的回答。
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線對齊。
看到這里大概已經明白了概念,align-content是針對flex容器里面多軸(多行)的情況,align-items是針對一行的情況進行排列。下面寫個小demo。
<div id="container">
<div id="One">1</div>
<div id="Two">2</div>
</div>
#container{
width:300px;
height:200px;
display: flex;
border:1px solid #000000;
flex-direction: row;
flex-wrap: wrap;
justify-content: space-around;
/*align-items: flex-start;*/
align-content: space-between;
}
#One,#Two{
width:200px;
height:30px;
border:1px solid red;
}
此時可以看到item的寬度相加大於container的寬度,容器中flex-wrap屬性值是wrap即會造成換行,換行后就會有多個crossAxis軸,這個時候就需要用到align-content,先看看結果。

可以看到align-content值生效了,如果是這時候使用align-items會是怎樣的效果呢?

align-items是id="One"的DIV生效,而第二個軸上的div沒有受到影響。
反之如果width相加小於container的寬度,那么就需要用align-items。align-content則不會生效。在不生效的情況下,兩個屬性都會去默認值stretch。

