文章目录
- 1.主轴对齐方式
- 1.1.justify-content:space-between; 两侧没缝隙
- 1.2.justify-content:space-around; 盒子平均分,比例1:2
- 1.3.justify-content:space-evenly; 盒子平均分,比例为1:1
- 1.4.justify-content: center; 经常用于让一个盒子水平居中
- 2.侧轴对齐方式
- 3.伸缩比
- 4.圣杯布局
- 5.总结
display: flex; 一定要给亲爸爸(父元素)style中添加。
<!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>
.box {
width: 1250px;
height: 200px;
margin: 100px auto;
background-color: pink;
/* 弹性容器 */
display: flex;
/* 主轴对齐方式 */
justify-content: space-between;
}
.box>div {
width: 250px;
height: 200px;
background-color: aqua;
}
.box>div:nth-child(2n) {
background-color: yellowgreen;
}
a {
width: 250px;
height: 200px;
background-color: blue;
}
/* 通过父元素,操作子元素,弹性布局 */
</style>
</head>
<body>
<div class="box">
<!-- 弹性盒子,默认放在一排 -->
<div>1</div>
<div>2</div>
<a href="#">3</a>
</div>
</body>
</html>
1.主轴对齐方式
属性值 | 作用 |
flex-start | 默认值, 起点开始依次排列 |
flex-end | 终点开始依次排列 |
center | 沿主轴居中排列 |
space-around | 弹性盒子沿主轴均匀排列, 空白间距均分在弹性盒子两侧 |
space-between | 弹性盒子沿主轴均匀排列, 空白间距均分在相邻盒子之间 |
space-evenly | 弹性盒子沿主轴均匀排列, 弹性盒子与容器之间间距相等 |
1.1.justify-content:space-between; 两侧没缝隙
1.2.justify-content:space-around; 盒子平均分,比例1:2
1.3.justify-content:space-evenly; 盒子平均分,比例为1:1
1.4.justify-content: center; 经常用于让一个盒子水平居中
2.侧轴对齐方式
属性值 | 作用 |
flex-start | 起点开始依次排列 |
flex-end | 终点开始依次排列 |
center | 沿侧轴居中排列 |
stretch | 默认效果, 弹性盒子沿着侧轴线被拉伸至铺满容器 |
可以让元素垂直居中。 |
可以通过flex让一个子盒子(块)水平和垂直居中。
.box {
width : 400px;
height : 400px;
margin : 100px auto;
background-color : red;
display : flex;
/* 主轴居中 */
justify-content : center;
/* 侧轴居中 */
align-items : center;
}
.box > div {
width : 200px;
height : 200px;
background-color : green;
}
3.伸缩比
把父盒子分为若干份数,每个子盒子各占几份。
flex:1; 一定给子盒子加
分配父级剩余的空间
flex: 1;
比如有一个父盒子里面有四个子盒子,每个子盒子写 flex:1; 此时每个子盒子各占四分之一。
.box {
width : 1200px;
height : 400px;
background-color : pink;
margin : 100px auto;
/* 弹性容器 */
display : flex;
}
/* 弹性盒子 */
.box > div {
/* 伸缩比,占的是父盒子的宽度,把他分成了等份 */
flex : 1;
/* 默认子盒子和父亲一样高 */
background-color : aqua;
}
<div class="box">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
</div>
注意:
一定要给子盒子添加。
子盒子默认高度会和父盒子一样高。(前提是不给高度)
4.圣杯布局
核心思路:
两侧盒子写固定大小
中间盒子 flex: 1; 占满剩余空间
.search {
width : 100%;
height : 50px;
display : flex;
}
.left {
width : 50px;
height : 50px;
background-color : yellowgreen;
}
.center {
flex : 1;
height : 50px;
background-color : red;
}
.right {
width : 50px;
height : 50px;
background-color : yellowgreen;
}
注意:中间flex: 1; 和 width 有冲突。 优先执行 flex:1;
5.总结
- flex眼中,标签不再分类。简单说就是没有块级元素,行内元素和行内块元素。任何一个元素都可以直接给宽度和高度一行显示。
- Flex不存在脱标的情况:也就是基本淘汰了浮动,更不用清除浮动。
- 当然存在兼容性问题,如果不考虑兼容性可以大量使用,如果是移动端则不用考虑直接flex。