定义
弹性盒子是CSS3的一种新的布局模式
CSS3弹性盒是一种当页面需要适应不同屏幕大小以及设备类型确保元素拥有恰当的行为的布局方式。
引入弹性盒布局模型的目的是提供一种更加有效的方式来对一个容器中的子元素进行排列、对齐和分配空白空间。
CSS弹性盒内容
弹性盒子由弹性容器和弹性子元素构成。
弹性容器通过设置display属性的值为flex将其定义为弹性容器。
弹性容器内包含了一个或多个弹性子元素。
弹性容器外及弹性子元素内是正常渲染的,弹性盒子只是定义了弹性子元素如何在弹性容器内布局。
默认弹性盒里内容横向摆放
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.container{
width: 400px;
height: 400px;
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="container">
<div class="box1"></div>
<div class="box2"></div>
<div class="box3"></div>
<div class="box4"></div>
</div>
</body>
</html>
在.container中加上display: flex;
父元素上的属性
display属性
display:flex; 开启弹性盒,属性设置后子元素默认水平排列。
flex-direction
定义:指定了弹性子元素在父容器中的位置。
语法
flex-direction:row|row-reverse|column|column-reverse
1、row:横向从左到右排列(左对齐),默认的排列方式。
2、row-reverse:反转横向排列(右对齐,从后往前排,最后一项排在最前面)
3、column:纵向排列
4、column-reverse:反转纵向排列,从后往前排,最后一排顶在上面
.container{ width: 400px; height: 400px; background-color: aquamarine; display: flex; flex-direction: column-reverse; }
justify-content属性
定义:应用在弹性容器上,把弹性项沿着弹性容器的主轴线对齐。
语法
justify-content:flex-start | flex-end | center
1、flex-start:弹性项目向行头紧挨着填充。这个是默认值。第一个弹性项的main-start外边距边线被放置在该行的main-start边线,而后续弹性项依次平齐摆放。
2、 flex-end:弹性项目向行尾紧挨着填充。第一个弹性项的main-end外边距边线被放置在该行的main-end边线,而后续弹性项依次平齐摆放。
3、center:弹性项目居中紧挨着填充。(如果剩余的自由空间是负的,则弹性项目将在两个方向上同时溢出)
.container{
width: 400px;
height: 400px;
background-color: aquamarine;
display: flex;
flex-direction: column;
justify-content: center;
}
align-items属性
定义:设置或检索弹性盒子元素在侧轴(纵轴方向)上的对齐方式
语法
align-items: center | flex-start | flex-end
1、flex-start:弹性盒子元素的纵轴起始位置的边界紧靠住该行的侧轴起始边界
2、 flex-end:弹性盒子元素的纵轴起始位置的边界紧靠住该行的侧轴结束边界
3、center:弹性盒子元素在该行的侧轴(纵轴)上居中放置。(如果该行的尺寸小于弹性盒子元素的尺寸,则会向两个方向溢出相同的长度)
.container{
width: 400px;
height: 400px;
background-color: aquamarine;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
子元素上的属性
flex-grow
根据弹性盒子元素所设置的元素所设置的扩展因子作为比率来分配剩余空间。
默认为0,即如果存在剩余空间,也不放大。
如果只有一个子元素设置,那么按扩展因子转化的百分比对其分配剩余空间。0.1即10%,1即100%,超出按100%
.box1{
width: 100px;
height: 100px;
background-color: red;
flex: 0.2;
}
.box2{
width: 100px;
height: 100px;
background-color: green;
flex: 0.6;
}
.box3{
width: 100px;
height: 100px;
background-color: blue;
flex: 0.2;
}
/* 用flex也可以 */
/* .box1{
width: 100px;
height: 100px;
background-color: red;
flex-grow: 1;
}
.box2{
width: 100px;
height: 100px;
background-color: green;
flex-grow: 3;
}
.box3{
width: 100px;
height: 100px;
background-color: blue;
flex-grow: 1;
} */