若给一个div设置display:flex;这个div就可以成为flex容器,在flex容器中用flex-direction,justify-content,align-items等属性对子div进行布局是十分方便的。
div是块级元素,默认一个div独占一行,可以通过在父级div(必须是flex容器)中设置flex-direction: row;让其在一行显示。
div1
div2
设置flex-direction: row;则可以让字div变为一列。
#box-container {
height: 500px;
display: flex;
flex-direction: column;
}
flex-direction: column;让子元素反向一行显示:
#box-container {
height: 500px;
display: flex;
flex-direction: row-reverse;
border: 1px solid black;
}
让子元素反向一列显示
#box-container {
height: 500px;
display: flex;
flex-direction: column-reverse;
border: 1px solid black;
}
justify-content的可选值包括:
justify-content: center;可让子元素居中显示。
#box-container {
height: 300px;
display: flex;
flex-direction: row;
justify-content: center;
border: 1px solid black;
}
若flex-direction:column;则为上下居中:
#box-container {
height: 300px;
display: flex;
flex-direction: column;
justify-content: center;
border: 1px solid black;
}
默认值
#box-container {
height: 300px;
display: flex;
flex-direction: row;
justify-content: flex-start;
border: 1px solid black;
}
从父元素尾部开始排列
#box-container {
height: 300px;
display: flex;
flex-direction: row;
justify-content: flex-end;
border: 1px solid black;
}
flex-direction: column;时的效果类似只不过从横向排列改为纵向排列,后面就不演示了。
子元素均匀排列,紧贴父元素头尾两端。
#box-container {
height: 300px;
display: flex;
flex-direction: row;
justify-content: space-between;
border: 1px solid black;
}
加入一个颜色为green的div3(其余属性和div1,div2完全一样),效果更明显:
子元素完全均匀排列,不紧贴父元素头尾两端。
#box-container {
height: 300px;
display: flex;
flex-direction: row;
justify-content: space-around;
border: 1px solid black;
}
align-items的可选值包括:
#box-container {
height: 300px;
display: flex;
flex-direction: row;
align-items: flex-start;
border: 1px solid black;
}
#box-container {
height: 300px;
display: flex;
flex-direction: row;
align-items: flex-end;
border: 1px solid black;
}
#box-container {
height: 300px;
display: flex;
flex-direction: row;
align-items: center;
border: 1px solid black;
}
#box-container {
height: 300px;
display: flex;
flex-direction: row;
align-items: stretch;
border: 1px solid black;
}
#box-1 {
background-color: dodgerblue;
/*width: 100px;*/
/*height: 100px;*/
}
#box-2 {
background-color: orangered;
/*width: 100px;*/
/*height: 100px;*/
}
#box-3 {
background-color: green;
width: 100px;
height: 100px;
}
取消div1和div2的宽高设置,在没有设置大小的情况下,align-items: stretch;时子元素铺满父元素:
#box-container {
height: 300px;
display: flex;
flex-direction: row;
align-items: baseline;
border: 1px solid black;
}
用以上属性可以很容易的对子级div进行布局,例如让子级div上下左右居中:
div1