flex容器与项目的认识和常用属性
flex容器与项目的认识
- 比如以下代码中(container:称之为容器)(top:称之为项目),给container设置display: flex;
<!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>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
:root {
font-size: 10px;
}
body {
font-size: 1.6rem;
}
.container {
border: 1px solid darkorange;
height: 40rem;
display: flex;
}
.container > .top {
border: 1px solid darkorange;
height: 20rem;
}
</style>
</head>
<body>
<div class="container">
<div class="top">我是第1</div>
<div class="top">我是第2</div>
<div class="top">我是第3</div>
<div class="top">我是第4</div>
</div>
</body>
</html>
- flex常用主轴上的对齐属性有以下
- 剩余空间左边,项目靠右边 (justify-content: flex-end;)
- 剩余空间为两边,项目居中(justify-content: center;)
- 二端对齐,剩余空间留在中间(justify-content: space-between;)
- 平均对齐,剩余空间都是平均的(justify-content: space-evenly;)
- 剩余空间左边,项目靠右边 (justify-content: flex-end;)
- flex常用交叉轴对齐属性有以下
- 剩余空间在上 项目在下(align-items: flex-end);
- 剩余空间为上下 项目居中(align-items: center;)
- 完全无弹性,也就是项目不能伸小扩大,为固定状态大小的意思,flex: none;
- 完全自适应,也就是项目能扩大伸小flex: 1;
-控制某个项目在交叉轴上的对齐(align-self: flex-start;为上)(align-self: flex-end;为下),居中就没啥用,因为本来就是居中(align-self: center;) - 这个属性很好玩 order: 1; 意思就是控制项目的顺序,默认状态是0,比如我把我是第一设置为order: 1;,那么它会跑到我是第4后面去
以下常用属性都用到的效果
- 剩余空间在上 项目在下(align-items: flex-end);
<!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>flex布局</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
:root {
font-size: 10px;
}
body {
font-size: 1.6rem;
}
.container {
border: 1px solid darkorange;
height: 40rem;
display: flex;
justify-content: space-evenly;
align-items: center;
}
.container > .top {
border: 1px solid darkorange;
height: 20rem;
width: 10rem;
}
.container > .top:nth-of-type(2) {
flex: none;
align-self: flex-start;
}
.container > .top:nth-of-type(3) {
flex: 1;
}
.container > .top:first-of-type {
order: 1;
background: aquamarine;
}
.container > .top:nth-of-type(4) {
align-self: flex-end;
}
</style>
</head>
<body>
<div class="container">
<div class="top">我是第1</div>
<div class="top">我是第2</div>
<div class="top">我是第3</div>
<div class="top">我是第4</div>
</div>
</body>
</html>