弹性盒子是CSS3
的一种新布局模式。
CSS3
弹性盒( Flexible Box
或 flexbox
),是一种当页面需要适应不同的屏幕大小以及设备类型时确保元素拥有恰当的行为的布局方式。Flex container
)和弹性子元素(Flex item
)组成。display
属性的值为 flex
或 inline-flex
将其定义为弹性容器。Flex
布局以后,子元素的float、clear
和vertical-align
属性将失效。flex
容器有两根轴:水平主轴就是x轴(main axis
)和竖直轴也是y轴(cross axis
)Flex
布局的元素,被称为Flex
容器(flex * container
),简称“容器”。其所有子元素自动成为容器成员,成为Flex
项目(Flex * item
),简称“项目”。用法详解:
flex-direction属性:决定主轴的方向(即项目的排列方向)
.box {
flex-direction: row | row-reverse | column | column-reverse;
}
flex-wrap属性:定义换行情况
默认情况下,项目都排列在一条轴线上,但有可能一条轴线排不下。
.box{
flex-wrap: nowrap | wrap | wrap-reverse;
}
nowrap(默认):不换行;
wrap:换行,第一行在上方;
wrap-reverse:换行,第一行在下方。
flex-flow属性:flex-direction和flex-wrap的简写,默认row nowrap
.box{
flex-flow: <flex-direction> || <flex-wrap>;
}
justify-content属性:定义项目在主轴上的对齐方式。
对齐方式与轴的方向有关,本文中假设主轴从左到右。
.box {
justify-content: start | end | flex-start | flex-end | center | left | right | space-between | space-around | space-evenly | stretch | safe | unsafe | baseline | first baseline | last baseline;
}
align-items属性:定义在交叉轴上的对齐方式
对齐方式与交叉轴的方向有关,假设交叉轴从下到上。
.box{
align-items: flex-start | flex-end | center | baseline | stretch;
}
align-content属性:定义多根轴线的对齐方式
修改 flex-wrap
属性的行为,类似 align-items
, 但不是设置子元素对齐,而是设置行对齐,如果项目只有一根轴线,该属性不起作用。所以,容器必须设置flex-wrap
:···;
项目的属性:设置在项目上的属性也有6个。
order - flex-grow - flex-shrink - flex-basis - flex - align-self
order属性:定义项目的排列顺序。
数值越小,排列越靠前,默认为0,可以是负值。
.item {
order: <整数>;
}
flex-grow属性:定义项目的放大比例 设置或检索弹性盒子元素的扩展比率。
flex-grow
的数值都相同,则等分剩余空间flex-grow
为2,其余都为1,则该项目占据剩余空间是其余的2倍flex-shrink属性:定义项目的缩小比例
flex-wrap
。flex
元素仅在默认宽度之和大于容器的时候才会发生收缩,其收缩的大小是依据 flex-shrink
的值。flex-basis属性:定义在分配多余空间之前,项目占据的主轴空间。
auto
,浏览器根据此属性检查主轴是否有多余空间。flex-basis
是分配多余空间之前项目占据的主轴空间,如果空间不足则默认情况下该项目也会缩小。
Flex属性是flex-grow
,flex-shrink
和flex-basis
的简写
默认值为0 1 auto,第一个属性必须,后两个属性可选。
.item{
flex: none | [<flex-grow><flex-shrink><flex-basis>];
}
可以用 flex:auto 代替 flex: 1 1 auto;;
可以用 flex: none 代替 flex: 0 0 auto;
align-self: 在弹性子元素上使用。覆盖容器的 align-items 属性。
单个项目有与其他项目不一样的对齐方式,可覆盖align-items
属性。默认值为auto
,表示继承父元素的align-items
属性,如果没有父元素,则等同于stretc
h
align-self: auto | flex-start | flex-end | center | baseline | stretch;
实用例子
flex-内容宽度等分
//css
.box {
display: flex;
}
.box div {
flex: 1;
border: 1px solid red;
}
//html
<div class="box">
<div>1</div>
<div>2</div>
<div>3</div>
</div>
未知高宽上下左右居中
html,
body {
height: 100%
}
.main {
display: flex;
height: 100%;
justify-content: center;
align-items: center
}
.box {
width: 300px;
border: 1px solid red;
}
//html
<div class="main">
<div class="box">未知高度上下左右居中</div>
</div>