Flex布局
弹性布局基本上能解决所有的布局方案。
基本概念
采用 Flex 布局的元素,称为 Flex 容器(flex container),简称"容器"。它的所有子元素自动成为容器成员,称为 Flex 项目(flex item),简称"项目"。
容器默认存在两根轴:水平的主轴(main axis)和垂直的交叉轴(cross axis)。主轴的开始位置(与边框的交叉点)叫做main start
,结束位置叫做main end
;交叉轴的开始位置叫做cross start
,结束位置叫做cross end
。
项目默认沿主轴排列。单个项目占据的主轴空间叫做main size
,占据的交叉轴空间叫做cross size
用法
父容器:
flex-direction
:row | row-reverse | column | column-reverse
定义主轴方向
flex-wrap
:nowrap | wrap | wrap-reverse
定义缠绕方式,即下一行如何换行
flex-flow
:<flew-direction> || <flex-wrap>
复合属性,flew-direction || flex-wrap
justify-content
:flex-start|flex-end|center |space-between|space-around
定义主轴上的对齐方式
align-items
:flex-start|flex-end|center|baseline|stretch
定义交叉轴上的对齐方式
align-content
:flex-start|flex-end|center |space-between|space-around
在wrap换行后,即多根轴线的对齐方式
子元素:
order
:数字表示排列顺序。数字越小,越靠前。
flex-grow
:数字计算占比,基于剩余空间放大元素。默认为0。
flex-shrink
:数字计算占比,基于不足空间缩小元素。默认为1。
flex-basis
:初始的尺寸。相当于width/height,默认auto
flex
:<flex-grow> | <flex-shrink> | <flex-basis>
复合属性,默认为“0 1 auto”
用Flex实现圣杯布局
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>弹性布局FLex--圣杯实例</title>
<style>
html{
height: 100%;
}
body{
height: 100%;
}
div{
border: 1px solid red;
}
#box{
display: flex;
flex-direction: column;
justify-content: space-between;
width: 100%;
height: 100%;
}
#body{
flex-grow: 1;
display: flex;
justify-content: space-between;
}
#middle{
flex-grow: 1;
}
#left,#right{
min-width: 23%;
}
#head,#foot{
min-height: 15%;
}
#left,#right,#head,#foot,#middle{
display: flex;
justify-content: center;
align-items: center;
}
</style>
</head>
<body>
<div id="box">
<div id="head">头</div>
<div id="body">
<div id="left">左</div>
<div id="middle">中</div>
<div id="right">右</div>
</div>
<div id="foot">底座</div>
</div>
</body>
</html>