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效果如下