基本樣式設置
父容器:display: flex;
子元素:justify-content、flex-flow
/* 設置父容器爲伸縮盒子 */
display: flex;
/* 設置子元素的排列方式 */
/* flex-start 讓子元素在起始位置排列
flex-end 讓子元素在末尾位置排列
center 讓子元素居中排列
space-between 讓子元素左右對齊父元素開始和結束位置,中間平均分隔
space-around 所有子元素左右間隔一樣*/
justify-content: space-around;
/* 設置行/列排列,達到最大寬度換行和倒置順序 */
/* row 行排列
cloumn 列排列
nowrap 不換行
wrap 換行
row-reverse 行排列並倒置順序
cloumn-reverse 列排列並倒置順序
wrap-reverse 換行並倒置順序*/
flex-flow:wrap;
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>flex</title>
<link rel="shortcut icon" href="favicon.ico">
<style>
body {
position: absolute;
left: 0px;
right: 0px;
top: 0px;
bottom: 0px;
}
.box {
width: 900px;
height: 900px;
border: 1px solid rgba(0, 0, 0, 0.3);
position: relative;
left: 0px;
right: 0px;
top: 0px;
bottom: 0px;
margin: auto;
/* 設置父容器爲伸縮盒子 */
display: flex;
/* 設置子元素的排列方式 */
/* flex-start 讓子元素在起始位置排列
flex-end 讓子元素在末尾位置排列
center 讓子元素居中排列
space-between 讓子元素左右對齊父元素開始和結束位置,中間平均分隔
space-around 所有子元素左右間隔一樣*/
justify-content: space-around;
/* 設置行/列排列,達到最大寬度換行和倒置順序 */
/* row 行排列
cloumn 列排列
nowrap 不換行
wrap 換行
row-reverse 行排列並倒置順序
cloumn-reverse 列排列並倒置順序
wrap-reverse 換行並倒置順序*/
flex-flow:wrap;
}
.box > div {
width: 200px;
height: 200px;
}
.box > div:nth-of-type(1) {
background-color: red;
}
.box > div:nth-of-type(2) {
background-color: green;
}
.box > div:nth-of-type(3) {
background-color: blue;
}
.box > div:nth-of-type(4) {
background-color: orange;
}
.box > div:nth-of-type(5) {
background-color: pink;
}
</style>
</head>
<body>
<div class="box">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
</div>
</body>
其他屬性
flex:比例值 讓各子元素按比例寬度填充父容器(經常被用到)
作用對象:子元素
.box > div {
width: 200px;
height: 200px;
}
.box > div:nth-of-type(1) {
background-color: red;
flex: 2;
}
.box > div:nth-of-type(2) {
background-color: green;
flex-shrink: 1;
flex: 3;
}
.box > div:nth-of-type(3) {
background-color: blue;
flex: 1;
}
.box > div:nth-of-type(4) {
background-color: orange;
flex: 2;
}
.box > div:nth-of-type(5) {
background-color: pink;
}
align-items
子元素在側軸方向(行排列則側軸爲垂直方向,列排列相反)對齊方式
align-items: center; 居中排列
屬性值:
flex-start 側軸開始位置
center 側軸中間位置
flex-end 側軸結束位置
baseline 內容基線位置
stretch 子元素填充側軸