CSS3 中的弹性盒子(flex)

118 阅读2分钟

弹性盒子

弹性盒子(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>

png

flex-direction:row-reverse

反转横向排列

flex-direction:row-reverse

png

flex-direction: column;

纵向排列

 flex-direction: column;
 

png

flex-direction: column-reverse;

反转纵向排列

flex-direction: column-reverse;

N@GA6_J$VP(G}%8K4%_PO0I.png

justify-content

justify——content定义了子弹性元素沿着弹性容器的主轴线对齐方式

属性值含义
flex-start紧靠左,默认值
flex-end紧靠后
center居中
space-between两端靠齐,中间均分
space-around首尾和弹性容器之间有一半间隔,中间均分

image.png

align-items

align-items定义了子弹性元素在弹性盒子元素侧轴方向上的对齐方式

属性值含义
flex-start紧靠侧轴起始位置
flex-end紧靠侧轴结束位置
center居中
baseline与基线对齐
stretch轴线占满整个交叉轴,默认

image.png

flex-wrap

属性值含义
nowrap弹性容器为单行,弹性子项会溢出弹性容器,默认
wrap弹性容器为多行,弹性子项溢出的部分会被放置到新行
wrap-reverse反转wrap

image.png

弹性盒子垂直居中属性

justify-content: centeralign-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>

1P86VQE.png