笔记
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.father-box {
width: 600px;
height: 150px;
background-color: #fff;
border: 2px solid black;
}
.child1 {
width: 100px;
height: 100px;
background-color: red;
}
.child2 {
width: 100px;
height: 100px;
background-color: blue;
}
.child3 {
width: 100px;
height: 100px;
background-color: green;
}
</style>
</head>
<body>
<div class="father-box">
<div class="child1"></div>
<div class="child2"></div>
<div class="child3"></div>
</div>
</body>
</html>
布局原理
通过给父盒子添加flex属性,来控制子盒子的位置和排列方式。
父元素的属性
display:flex
这是flex布局的基础,想要给哪些盒子布局就在它们的父盒子上添加display:flex;
<style>
.father-box {
display: flex;
}
</style>
flex-direction:row / row-reverse / column / coloumn-reverse;
设置哪个为主轴则另一方就为侧轴,其中:
row:设置以横轴为主轴(电脑屏幕水平为横轴),且子元素默认排列为起始到结束,也就是从左往右
row-reverse:设置子元素排列为从结束为止到开始,也就是从右往左
column也就相似
.father-box {
display: flex;
flex-direction: row;
width: 600px;
height: 300px;
background-color: #fff;
border: 2px solid black;
}
justify-content:flex-star / flex-end / flex-center / space-around / space-between
设置子元素在主轴上的对齐方式,其中:
flex-start/end:设置子元素贴着起始边排列
flex-center:设置子元素居中对齐
space-around:子元素平分剩余的空间,指的是每个子元素的左右两侧平分的空间相等
space-between:子元素贴着起始和结束两边对齐,中间的空间平均分配
代码示例:
justify-content:space-between
.father-box {
display: flex;
justify-content: space-between;
width: 600px;
height: 300px;
background-color: #fff;
border: 2px solid black;
}
效果
代码示例:
justify-content:space-around
.father-box {
display: flex;
justify-content: space-around;
width: 600px;
height: 150px;
background-color: #fff;
border: 2px solid black;
}
效果
flex-warp:nowrap / warp;
设置子元素是否会在父元素一行装不下时是否换行
ps:在默认情况下是不换行的,也就是说,当子元素在父元素中一行装不下时,会自动压缩子元素使得一直在一行排列
align-items:center / flex-start / strentch…
这个就与横轴排列十分的相似
strentch就是拉伸元素,去掉侧轴的高度或者宽度,子元素会自动与父元素一样大align-content:flex-start / center …
都是相似的
ps:最后值得注意的是align-items是设置单行子元素,而align-content是设置多行的
**flex-flow:flex-direction flex-warp;
复合属性用来方便直接写排列方向和换行,减少代码的行数
子元素的属性
flex:number;
设置子元素在父元素中划分后,应该占据多少份,默认number为零
代码示例
.child1 {
flex: 2;
width: 100px;
height: 100px;
background-color: red;
}
效果
align-self:flex-start/end…
与之前的相似
order:number;
定义子元素的排列顺序,数字越小就排列在前面,默认为零
代码示例
.child3 {
order: -1;
width: 100px;
height: 100px;
background-color: green;
}
效果