弹性盒子模型是CSS3的一种新的布局模式,弹性盒是一种当页面需要适应不同的屏幕大小以及设备类型时确保拥有合适的布局方式,引入弹性盒子模型的目的时提供更加有效的方式来对一个容器中的子元素进行排列,对齐和分配空白空间。
弹性盒子由弹性容器(Flex container) 和弹性子元素(Flex item)组成。弹性容器通过设置display属性的值为flex将其定义为弹性容器,弹性容器包含了一个或多个弹性子元素。
注意:弹性容器外及弹性子元素内是正常渲染的,弹性盒子只是定义了弹性子元素如何在弹性容器内布局。
display属性
开启弹性盒子
html
display: flex;
未开启弹性盒子如下
html
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.continer{
width: 500px;
height: 500px;
background-color: aquamarine;
}
.box1{
width: 100px;
height: 100px;
background-color: red;
}
.box2{
width: 100px;
height: 100px;
background-color: green;
}
.box3{
width: 100px;
height: 100px;
background-color: blue;
}
</style>
</head>
<body>
<div class="continer">
<div class="box1"></div>
<div class="box2"></div>
<div class="box3"></div>
</div>
</body>

开启弹性盒子

flex-direction属性
指定弹性子元素在父容器中的位置
row: 横向从左到右排列(左对齐),这是默认排列方式。
row-reverse:反转横向排列(右对齐,从后往前排列,最后一项排在最前面)
column:纵向排列
colimn-reverse:反转纵向排列
html
flex-direction: row-reverse;

css
flex-direction:column;

css
flex-direction:column-reverse;

justify-content属性
内容对齐属性,应用在弹性容器上,把弹性项沿着弹性容器的株洲县对齐。
flex-start: 弹性项向行头紧挨着,这个是默认值。
flex-end:弹性项向行尾紧挨着填充。
center: 弹性项居中紧挨着。(如果剩余的自由空间是负的,则弹性项将在两个方向上同时溢出)
css
justify-content: flex-end;

css
justify-content: center;

align-items属性
设置或检索弹性盒子子元素在侧轴(纵轴)上的对齐方式。
flex-start:弹性盒子子元素的侧轴(纵轴)起始位置的边界靠住的纵轴其实边界。
flex-end: 弹性盒子子元素的侧轴(纵轴)起始位置的边界靠住的该行纵轴其实边界。
center:弹性盒子元素在该行的侧轴(纵轴)上居中的位置。(如果该行的尺寸小于弹性盒子的尺寸,则会向两个方向溢出相同的长度)。
css
align-items: flex-start;

css
align-items: flex-end;

css
align-items: center;

flex-grow 或flex属性(用于子元素)
根据弹性盒子元素所设置的扩展因子做为比率来分配剩余空间,默认为0。即如果存在剩余空间也不会放大。如果只有一个子元素设置,那么按扩展因子转化的百分比对其分配剩余空间,0.1即为10%,1为100%,超出按100%计算。
html
<style>
.continer{
width: 500px;
height: 500px;
background-color: aquamarine;
display: flex;
}
.box1{
width: 100px;
height: 100px;
background-color: red;
flex: 0.3;
}
.box2{
width: 100px;
height: 100px;
background-color: green;
flex: 0.3;
}
.box3{
width: 100px;
height: 100px;
background-color: blue;
flex: 0.4;
}
</style>
</head>
<body>
<div class="continer">
<div class="box1"></div>
<div class="box2"></div>
<div class="box3"></div>
</div>
</body>
