本篇属于css学习笔记,在学习flex布局时有一些经常用到的属性,如果长期不用就会遗忘,在这里做一下记录,方便以后查看,欢迎大家提出意见。
flex is a new value added to the CSS display property. Along with inline-flex it causes the element that it applies to to become a flex container, and the element’s children to each become a flex item. The items then participate in flex layout, and all of the properties defined in the CSS Flexible Box Layout Module may be applied.
基本概念
当给一个 element
设置 display:flex
属性时, 它本身就变成了一个 flex container
, 而它的子元素就成为 flex item
, flex
有很多属性可以用来对 flex item
进行布局,明白了这个基本原理,我们学习 flex
就很简单,只需要查看对应 flex property
的用法就可以。
常用flex property
flex direction
控制flex item横行排列还是纵向排列,以及排列时各元素的顺序,对应的值有: row、 column、 row-reverse和column-reverse。
<style>
#box-container {
display: flex;
height: 500px;
flex-direction: row-reverse;
}
#box-1 {
background-color: dodgerblue;
width: 50%;
height: 50%;
}
#box-2 {
background-color: orangered;
width: 50%;
height: 50%;
}
</style>
<div id="box-container">
<div id="box-1"></div>
<div id="box-2"></div>
</div>
justify-content
使用这个属性首先要明白主轴(main axis)的概念,即如果 flex-direction:row
,主轴为水平线,反之为垂直的线,justify-content 会将flex items按照main axis进行对齐,默认对齐值为start,即巨左对齐。
具体示例可以参考MDN
align-items
这个属性和justify-content类似,也是对flex items进行对齐操作,不过其对齐时沿着cross axis(即main axis对垂直方向)进行。
shorthand
The flex property is a shorthand for the flexbox properties flex-grow, flex-shrink and flex-basis.