justify-content:设置主轴上子元素的排列方式
justify-content 的属性值如下:
属性值 | 含义 |
---|---|
flex-start | 从主轴的头部开始排,主轴:x轴 左对齐;y轴 顶部对齐(默 认值) |
flex-end | 从主轴的尾部开始排,主轴:x轴 右对齐;y轴 底部对齐 |
center | 在主轴上居中对齐 |
space-around | 平分主轴上的剩余空间 |
space-between | 先占据主轴的两边,再平分剩余的空间 |
1
2
3
div{
display: flex;
width: 800px;
height: 300px;
background-color: orange;
justify-content: flex-start;
}
div span{
width: 150px;
height: 100px;
background: skyblue;
}
运行结果:主轴是x轴,这种情况下子元素在主轴上表现为左对齐(默认值,可不写)
1
2
3
div{
display: flex;
width: 800px;
height: 300px;
background-color: orange;
justify-content: flex-end;
}
div span{
width: 150px;
height: 100px;
background: skyblue;
}
运行结果:主轴是x轴,这种情况下子元素在主轴上表现为右对齐
1
2
3
div{
display: flex;
width: 800px;
height: 300px;
background-color: orange;
justify-content: center;
}
div span{
width: 150px;
height: 100px;
background: skyblue;
}
运行结果:主轴是x轴,这种情况下子元素在主轴上表现为居中对齐
1
2
3
div{
display: flex;
width: 800px;
height: 300px;
background-color: orange;
justify-content: space-around;
}
div span{
width: 150px;
height: 100px;
background: skyblue;
}
运行结果:主轴是x轴,这种情况下子元素在主轴上平均分配了主轴剩余的空间,即每个子元素都分配了相同的外边距(左右)
1
2
3
div{
display: flex;
width: 800px;
height: 300px;
background-color: orange;
justify-content: space-between;
}
div span{
width: 150px;
height: 100px;
background: skyblue;
}
运行结果:主轴是x轴,这种情况下子元素首先贴住主轴(父元素)的两边,再平分主轴剩余空间
1
2
3
div{
display: flex;
width: 800px;
height: 400px;
background-color: orange;
flex-direction: column; /*将主轴设为y轴*/
justify-content: flex-start;
}
div span{
width: 150px;
height: 100px;
background: skyblue;
}
运行结果:主轴是y轴,这种情况下子元素在主轴上表现为顶部对齐(默认值,可不写)
1
2
3
div{
display: flex;
width: 800px;
height: 400px;
background-color: orange;
flex-direction: column; /*将主轴设为y轴*/
justify-content: flex-end;
}
div span{
width: 150px;
height: 100px;
background: skyblue;
}
运行结果:主轴是y轴,这种情况下子元素在主轴上表现为底部对齐
1
2
3
div{
display: flex;
width: 800px;
height: 400px;
background-color: orange;
flex-direction: column; /*将主轴设为y轴*/
justify-content: center;
}
div span{
width: 150px;
height: 100px;
background: skyblue;
}
运行结果:主轴是y轴,这种情况下子元素在主轴上表现为居中对齐
1
2
3
div{
display: flex;
width: 800px;
height: 400px;
background-color: orange;
flex-direction: column; /*将主轴设为y轴*/
justify-content: space-around;
}
div span{
width: 150px;
height: 100px;
background: skyblue;
}
运行结果:主轴是y轴,这种情况下子元素在主轴上平均分配了主轴上剩余的空间,即每个子元素都分配了相同的外边距(上下)
1
2
3
div{
display: flex;
width: 800px;
height: 400px;
background-color: orange;
flex-direction: column; /*将主轴设为y轴*/
justify-content: space-between;
}
div span{
width: 150px;
height: 100px;
background: skyblue;
}
运行结果:主轴是y轴,这种情况下子元素首先贴住主轴(父元素)的两边,再平分主轴剩余空间
注意:justify-content只会改变的是整个子元素在主轴上的排列方式,或左对齐,或右对齐,或顶部对齐,或底部对齐,或居中对齐等等,并不会改变子元素之间的排列顺序。