「这是我参与11月更文挑战的第2天,活动详情查看:2021最后一次更文挑战」
CSS3新推出了两种布局方式,分别是flex布局和grid布局,今天就先主要说明flex布局。
flex布局
flex布局的使用还是很简单的,只需要在父元素上声明display:flex,这样该父元素的所有直系子元素就都成为了flex元素。flex布局操作简单,并且对于一些特殊布局也非常容易实现,比如说垂直居中,并且它还不需要依赖position,float,display等属性。
轴
flex布局舍弃了top,bottom,left,riight这些方位词,而是引入了轴系统,就像平面直角坐标系中的x,y轴一样,只不过在这里叫做主轴和交叉轴,flex-start代表轴的起点位置,flex-end代表轴的终点位置,如果轴是从左到右,它们两个就代表左端和右端,如果轴是从上到下,就代表顶端和底端。
flex-direction是用于设置主轴方向,它的默认值是row,表示从左到右延伸,还有一个值是column表示从上到下延伸,主要主轴的方向确定,那么交叉轴的方向也就随之确定了。
严格说,justify-content:center表示子元素在主轴方向上居中,align-items:center表示子元素在交叉轴方向上居中。但是随着主轴方向的变化,这两个属性的含义也会随之改变。
总结一下~
| 主轴方向 | flex-direction | justify-content:center | align-items:center |
|---|---|---|---|
| 从左到右 | row | 水平居中 | 垂直居中 |
| 从上到下 | columm | 垂直居中 | 水平居中 |
来个例子吧~
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
div{
font-size: 15px;
display: flex;
align-items: center;
width: 35em;
height: 7em;
margin: 2em;
background-color: skyblue;
}
div span{
width: 5em;
height: 5em;
border-radius: 50%;
background-color: lightyellow;
}
/* 使用结构化伪类选择器中的nth-child选择器 */
div:nth-child(1){justify-content:flex-end;} /* 居右 */
div:nth-child(2){justify-content: flex-start;} /* 居左 */
div:nth-child(3){justify-content: space-around;} /* 元素平均排列,首尾两元素与容器边框的距离是元素之间间距的一半 */
div:nth-child(4){justify-content: space-between;} /* 首位两元素挨着容器壁,其他元素平均排列 */
</style>
</head>
<body>
<div>
<span></span>
<span></span>
<span></span>
</div>
<div>
<span></span>
<span></span>
<span></span>
</div>
<div>
<span></span>
<span></span>
<span></span>
</div>
<div>
<span></span>
<span></span>
<span></span>
</div>
</body>
</html>