弹性盒子
弹性盒子(flex box),是 css3 中引入的新布局模式。
弹性盒子决定了元素在页面上的排序,使它们能在不同屏幕大小以及设备类型时确保元素拥有恰当的布局方式。
弹性盒子的组成
弹性盒子是由弹性容器和弹性子元素组成的。
弹性盒子通过设置display的值为flex来将其定义为弹性容器。
flex-direction
flex-direction
指定了弹性容器中的弹性子元素在父容器中的位置
属性值 | 含义 |
---|---|
row | 横向从左到右排列(左对齐),默认的排列方式。 |
row-reverse | 反转横向排列(右对齐,从后往前排,最后一项排在最前面) |
column | 纵向排列 |
column-reverse | 反转纵向排列(从后往前排,最后一项排在最上面) |
flex-direction:row
横向排列
css:
.container {
display: flex;
flex-direction: row;
width: 400px;
height: 250px;
background-color: greenyellow;
}
.flex-item {
background-color: red;
width: 100px;
height: 100px;
margin: 10px;
}
html:
<div class="container">
<div class="flex-item">div1</div>
<div class="flex-item">div2</div>
<div class="flex-item">div3</div>
</div>
flex-direction:row-reverse
反转横向排列
flex-direction:row-reverse
flex-direction: column;
纵向排列
flex-direction: column;
flex-direction: column-reverse;
反转纵向排列
flex-direction: column-reverse;
justify-content
justify——content
定义了子弹性元素沿着弹性容器的主轴线对齐方式
属性值 | 含义 |
---|---|
flex-start | 紧靠左,默认值 |
flex-end | 紧靠后 |
center | 居中 |
space-between | 两端靠齐,中间均分 |
space-around | 首尾和弹性容器之间有一半间隔,中间均分 |
align-items
align-items
定义了子弹性元素在弹性盒子元素侧轴方向上的对齐方式
属性值 | 含义 |
---|---|
flex-start | 紧靠侧轴起始位置 |
flex-end | 紧靠侧轴结束位置 |
center | 居中 |
baseline | 与基线对齐 |
stretch | 轴线占满整个交叉轴,默认 |
flex-wrap
属性值 | 含义 |
---|---|
nowrap | 弹性容器为单行,弹性子项会溢出弹性容器,默认 |
wrap | 弹性容器为多行,弹性子项溢出的部分会被放置到新行 |
wrap-reverse | 反转wrap |
弹性盒子垂直居中属性
设justify-content: center
和align-items: center
css:
.container {
display: flex;
justify-content: center;
align-items: center;
width: 400px;
height: 250px;
background-color: greenyellow;
}
.flex-item {
background-color: red;
width: 100px;
height: 100px;
margin: 10px;
}
html:
<div class="container">
<div class="flex-item">div1</div>
<div class="flex-item">div2</div>
<div class="flex-item">div3</div>
</div>