1.任何一个flexbox布局的第一步是需要创建一个flex容器。为此给元素设置display
属性的值为flex
。在Safari浏览器中,你依然需要添加前缀-webkit
。
.flexcontainer {
display: -webkit-flex;
display: flex;
}
2.Flex项目是Flex容器的子元素。他们沿着主要轴和横轴定位。默认的是沿着水平轴排列一行。你可以通过flex-direction
来改变主轴方向修改为column
,其默认值是row
。
.flexcontainer {
display: -webkit-flex;
display: flex;
-webkit-flex-direction: row;
flex-direction: row;
}
.flexcontainer {
display: -webkit-flex;
display: flex;
-webkit-flex-direction: column;
flex-direction: column;
}
3.将flex项目移动到顶部,取决于主轴的方向。如果它是垂直的方向通过align-items
设置;如果它是水平的方向通过justify-content
设置。
.flexcontainer {
display: -webkit-flex;
display: flex;
-webkit-flex-direction: row;
flex-direction: row;
-webkit-align-items: flex-start;
align-items: flex-start;
}
4.flex项目称动到左边或右边也取决于主轴的方向。如果flex-direction
设置为row
,设置justify-content
控制方向;如果设置为column
,设置align-items
控制方向。 4.1移动到左边
.flexcontainer {
display: -webkit-flex;
display: flex;
-webkit-flex-direction: row;
flex-direction: row;
-webkit-justify-content: flex-start;
justify-content: flex-start;
}
.flexcontainer {
display: -webkit-flex;
display: flex;
-webkit-flex-direction: column;
flex-direction: column;
-webkit-align-items: flex-start;
align-items: flex-start;
}
4.2移动到右边
.flexcontainer {
display: -webkit-flex;
display: flex;
-webkit-flex-direction: row;
flex-direction: row;
-webkit-justify-content: flex-end;
justify-content: flex-end;
}
.flexcontainer {
display: -webkit-flex;
display: flex;
-webkit-flex-direction: column;
flex-direction: column;
-webkit-align-items: flex-end;
align-items: flex-end;
}
5.水平垂直居中。通过设置justify-content
或者align-items
为center
。另外根据主轴的方向设置flex-direction
为row
或column
.flexcontainer {
display: -webkit-flex;
display: flex;
-webkit-flex-direction: row;
flex-direction: row;
-webkit-align-items: center;
align-items: center;
-webkit-justify-content: center;
justify-content: center;
}
.flexcontainer {
display: -webkit-flex;
display: flex;
-webkit-flex-direction: column;
flex-direction: column;
-webkit-align-items: center;
align-items: center;
-webkit-justify-content: center;
justify-content: center;
}
6.相对于flex容器实现自动的伸缩,需要给每个flex项目设置flex
属性设置需要伸缩的值。
.flexcontainer {
display: -webkit-flex;
display: flex;
-webkit-flex-direction: row;
flex-direction: row;
-webkit-align-items: center;
align-items: center;
-webkit-justify-content: center;
justify-content: center;
}
.flexcontainer {
display: -webkit-flex;
display: flex;
-webkit-flex-direction: column;
flex-direction: column;
-webkit-align-items: center;
align-items: center;
-webkit-justify-content: center;
justify-content: center;
}