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线对齐。 


感觉这样翻译了之后还是略微有些抽象,不过有一个重点就是多行, 


下面我们来写一个小的例子。


1 <div class="child-1">
2     <div class="child-2">                   
3     </div>
4     <div class="child-2">                   
5     </div>
6 </div>

html结构如上。 
如果child-1的width设置为100px,child-2的width设置为30px,这样child-2会排列在一排上,具体的css如下


 1 <style type="text/css">
 2         *{
 3             margin:0px;
 4             padding: 0px;
 5         }
 6         div{
 7             border: 1px solid #0f0f0f;
 8         }
 9         .child-1{
10             margin: 30px auto;
11             display: flex;
12             width: 100px;
13             height: 60px;
14             justify-content: space-around;
15             align-content: center;
16         }
17         .child-2{
18             width: 30px;
19             height: 20px;
20         }
21     </style>

 

 

最终的结果如下图 
这里写图片描述

所以对于只有一行的flex元素,align-content是没有效果的,如果.child-1改用align-items:center;则会达到预期的效果,如下图 
这里写图片描述

但如果变成多行容器 
使用align-items时效果如下 
这里写图片描述 
使用align-content效果如下 
这里写图片描述

 

学习资源:flex布局中 align-items 和 align-conten t的区别

posted @ 2016-08-13 10:52  小车厂  阅读(769)  评论(0编辑  收藏  举报