目标: 能够使用Flex布局模型 灵活 、 快速 的开发网页
Flex布局又称弹性布局,是浏览器 提倡 的布局,使得布局更加 简单、灵活 ,还能 避免浮动脱标 问题。当容器高度不确定时,使用float浮动布局进行横向排列会导致脱离文档流,这时就可以使用flex布局。
重点概括:
- 添加弹性布局:display:flex;
- 主轴居中:justify-content: center;
- 主轴间距在子级之间:justify-content: space-between;
- 主轴所有地方的间距都相等:justify-content: space-evenly;
- 主轴间距包围在两侧:justify-content: space-around;
- 侧轴居中:align-items: center;
- 侧轴某子级居中:align-self:center;
- 子级无宽度时,子级宽度为内容宽度
- 子级无高度时,子级高度为容器高度
使用方式:
父元素添加 display:flex ,子元素可以自动挤压或拉伸。
组成成分:
- 弹性容器(父级)
- 弹性盒子(子级)
- 主轴
- 侧轴/交叉轴
<body>
<div class="box">
<div>1</div>
<div>2</div>
<div>3</div>
</div>
</body>
<style>
* {
margin: 0;
padding: 0;
}
.box {
/* 视觉效果: 子级一行排列/水平排列 */
/* 水平排列: 默认主轴在水平, 弹性盒子都是沿着主轴排列 */
display: flex;
height: 200px;
margin-top: 30px;
border: 1px solid #000;
}
.box div {
/*子级没有设置宽度时,盒子宽度为内容宽度*/
/*width: 100px;*/
height: 100px;
background-color: pink;
}
</style>
只是添加flex,子元素自动挤压
子级无宽度时
在Flex布局模型中,可以调节 主轴或侧轴的对齐方式 来设置盒子之间的间距。
主轴对齐方式:
给 父元素添加 justify-content:属性值;
<body>
<div class="box">
<div>1</div>
<div>2</div>
<div>3</div>
</div>
</body>
<style>
* {
margin: 0;
padding: 0;
}
.box {
display: flex;
/* 效果1:居中 */
/*justify-content: center;*/
/* 效果2:间距在弹性盒子(子级)之间 */
/*justify-content: space-between;*/
/* 效果3:所有地方的间距都相等 */
/*justify-content: space-evenly;*/
/* 效果4:间距包围在子级的两侧 */
/* 视觉效果: 子级之间的距离是父级两头距离的2倍 */
justify-content: space-around;
width: 400px;
height: 200px;
margin:30px auto;
border: 1px solid #000;
}
.box div {
width: 100px;
height: 100px;
background-color: pink;
}
</style>
侧轴对齐方式:
- 控制所有子级:给父元素添加 align-items:属性值;
- 控制某个子级:给子元素添加 align-self:属性值;
子级没有高度时,高度将被拉伸至与父级同高。
<body>
<div class="box">
<div>1111</div>
<div>2</div>
<div>3</div>
</div>
</body>
<style>
* {
margin: 0;
padding: 0;
}
.box {
display: flex;
/* 效果1:子级全部居中 */
/* align-items: center; */
/* 效果3:拉伸,默认值(现有状态,测试的时候去掉子级的高度) */
align-items: stretch;
width: 400px;
height: 200px;
margin: 30px auto;
border: 1px solid #000;
}
.box div {
width: 100px;
/* height: 100px; */
background-color: pink;
}
/* 效果2:单独设置某个弹性盒子的侧轴对齐方式 */
.box div:nth-child(2) {
/* align-self:center ; */
}
</style>
伸缩比:
给子元素添加 flex:整数值; 整数值为占有父级剩余尺寸的份数。
<body>
<div class="box">
<div>1</div>
<div>2</div>
<div>3</div>
</div>
</body>
<style>
* {
margin: 0;
padding: 0;
}
.box {
display: flex;
width: 400px;
height: 300px;
margin: 30px auto;
border: 1px solid #000;
}
.box div {
height: 200px;
margin: 0 10px;
background-color: pink;
}
.box div:nth-child(1) {
width: 50px;
}
.box div:nth-child(2) {
/* 占用父级剩余尺寸的份数 */
flex: 3;
}
.box div:nth-child(3) {
flex: 1;
}
</style>
上面这段代码,子级1为固定宽度,子级2、3为占额宽度。父级宽度减去子级1所占大小及子级2和子级3外边距大小后,剩余尺寸分为3+1=4份,其中子级2宽度占3份,子级3宽度占1份。父级剩余尺寸可以随意划分整数份,1+2、3+4、2+7等都是可以的。