flex布局
flex:主轴和辅轴
主轴:确认排列的方向(默认水平排列)
辅助:与主轴垂直的方向称为辅轴
示例
flex布局
<ul>
<li>home</li>
<li>movie</li>
<li>star</li>
</ul>
<style>
ul{
list-style: none;
display: flex;
height: 50px;
background: #ccc;
}
ul>li{
border:1px solid #000;
}
</style>
效果如下
flex属性
1、flex-direction:设置主轴方向 (默认flex-direction:row)
ul{
flex-direction: row-reverse;
list-style: none;
display: flex;
height: 50px;
background: #ccc;
}
2、justify-content:设置主轴的排布方式(默认justify-content:flex-start)
ul{
list-style: none;
display: flex;
justify-content: space-between;
height: 50px;
background: #ccc;
}
但是不允许这些关键字指定个别项的排布,但是子项可以使用auto外边距布局方式
如:
li:first-child{
margin-right:auto;
}
3、align-item:设置辅轴的对齐方式(默认:align-item:stretch)
ul{
list-style: none;
display: flex;
justify-content: space-between;
align-items: center;
height: 50px;
background: #ccc;
}
可以设置个别项的对齐方式,如:
li:first-child{
align-self: flex-start;
}
4、flex-basis、flex-grow、flex-shrink可伸缩尺寸
flex-basis:主轴方向上,经‘修正’前的‘首选’大小(默认auto:从对应的属性(width或height)获取到的尺寸;如果没有设置尺寸,根据其内容大小获取尺寸)
flex-grow:弹性系数(默认为0)。在flex-basis设置完首选大小之后,如果还有剩余空间,该系数表示如何处理剩余空间的分配
flex-shrink(默认为1):弹性系数,与flex-grow相反。空间不够,如何分配问题
flex-basis:auto情况
示例:
//flex-grow:1 剩余空间1:1分配
<style>
ul{
list-style: none;
display: flex;
height: 50px;
background: #ccc;
line-height: 50px;
width: 500px;
}
ul>li{
border:1px solid #000;
box-sizing: border-box;
flex-grow: 1;
}
li:first-child{
width: 100px;
}
li:nth-child(2){
width: 300px;
}
</style>
<body>
<ul>
<li>short</li>
<li>long</li>
</ul>
</body>
//base 剩余空间1:3分配
ul>li{
border:1px solid #000;
box-sizing: border-box;
}
li:first-child{
width: 100px;
flex-grow: 1;
}
li:nth-child(2){
width: 300px;
flex-grow: 3;
}
flex-basis:0情况
在flex-basis为0的情况下,第一设置的内容宽度大小将不会生效,只有第二步的flex-grow的值才会生效
ul>li{
border:1px solid #000;
box-sizing: border-box;
flex-basis: 0;
flex-grow: 1;
}
li:first-child{
width: 100px;
}
li:nth-child(2){
width: 300px;
}
ul>li{
flex:1 0 0%; //分别代表 flex-grow flex-shrink flex-basis;其中在简写情况下,flex-basis必须单位(百分号或者px)
}
// flex:1;表示:flex-grow:1; flex-shrink:1; flex-basis:0
flex-shrink计算方法
li:first-child{
flex:1 1 200px
}
li:nth-child(2){
flex:1 1 500px;
}
计算方法:
自己的(flex-shrinkflex-basis)/每项的(flex-shrinkflex-basis)的乘积之和 * 超出的宽度
(flex-shrinkflex-basis)/((flex-shrinkflex-basis)+(flex-shrinkflex-basis)) * 超出的宽度
(1200)/((1200)+(1500)) * 200
(1500)/((1200)+(1*500)) * 200
5、多行的flex布局
5.1 flex-warp:是否折行
5.2 align-content:多行情况下,辅轴的对齐方式
<style>
ul {
list-style: none;
display: flex;
height: 100px;
width: 800px;
align-items: flex-start;
flex-wrap: wrap;
background: #ccc;
}
ul>li {
border:1px solid #000;
width: 190px;
margin-right: 10px;
box-sizing: border-box;
align-content: space-between
}
</style>
<body>
<ul>
<li>title1</li>
<li>title2</li>
<li>title3</li>
<li>title4</li>
<li>title5</li>
<li>title6</li>
<li>title7</li>
<li>title8</li>
<li>title9</li>
</ul>
</body>
5.3 order个别元素的顺序排列 (默认 0)
数值越小,元素越排在前面
li:nth-child(5){
order:-1
}