flex佈局中align-items 和align-content的區別

參考資料:http://stackoverflow.com/questions/31250174/css-flexbox-difference-between-align-items-and-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效果如下
這裏寫圖片描述

發佈了44 篇原創文章 · 獲贊 117 · 訪問量 28萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章