前言
在 CSS Flexbox 布局中,align-items 和 justify-content 是两个非常基础,但又非常重要的概念。本文将会对这两个属性进行详细讲解,包括区别、用法以及示例代码。希望能够帮助读者更好地理解并使用 CSS Flexbox 布局。
align-items 和 justify-content 介绍
align-items 和 justify-content 是 CSS Flexbox 中用于设置元素在交叉轴和主轴上的位置和排列方式的两个属性。其中,align-items 用于设置元素在交叉轴上的位置和排列方式,而 justify-content 则用于设置元素在主轴上的位置和排列方式。
align-items
align-items 属性用于设置元素在交叉轴上的位置和排列方式。交叉轴是 Flexbox 布局中与主轴垂直的轴线。align-items 可以取以下不同的值:
flex-start- 元素在交叉轴起点对齐。flex-end- 元素在交叉轴终点对齐。center- 元素在交叉轴居中对齐。baseline- 元素按照基线对齐。stretch- 元素沿着交叉轴拉伸以填充剩余空间。
下面是一个示例,演示了不同的 align-items 值是如何影响元素在交叉轴上的排列方式的:
<div class="container"> <div class="item item1"></div> <div class="item item2"></div> <div class="item item3"></div> </div>
// www.javascriptcn.com code example
.container {
display: flex;
height: 400px;
align-items: center;
}
.item {
width: 100px;
height: 100px;
}
.item1 {
background-color: red;
}
.item2 {
background-color: blue;
}
.item3 {
background-color: green;
}上面的代码使用了 align-items: center 来让元素在交叉轴上居中对齐。结果如下:

justify-content
justify-content 属性用于设置元素在主轴上的位置和排列方式。主轴是 Flexbox 布局的主要轴线。justify-content 可以取以下不同的值:
flex-start- 元素在主轴起点处对齐。flex-end- 元素在主轴终点处对齐。center- 元素在主轴中间对齐。space-between- 元素之间均匀分布,第一个元素在起点,最后一个元素在终点。space-around- 元素均匀分布,相邻两个元素间距相等,元素到边缘间距为相邻两个元素间距的一半。space-evenly- 元素均匀分布,相邻两个元素和元素到边缘的间距相等。
下面是一个示例,演示了不同的 justify-content 值是如何影响元素在主轴上的排列方式的:
<div class="container"> <div class="item item1"></div> <div class="item item2"></div> <div class="item item3"></div> </div>
// www.javascriptcn.com code example
.container {
display: flex;
justify-content: space-between;
width: 400px;
height: 200px;
}
.item {
width: 100px;
height: 100px;
}
.item1 {
background-color: red;
}
.item2 {
background-color: blue;
}
.item3 {
background-color: green;
}上面的代码使用了 justify-content: space-between 来让元素在主轴上均匀分布。结果如下:

align-items 和 justify-content 的区别
虽然 align-items 和 justify-content 都用于设置元素在 Flexbox 布局中的位置和排列方式,但二者又有很大的区别。
align-items 用于设置元素在交叉轴上的位置和排列方式,而 justify-content 则用于设置元素在主轴上的位置和排列方式。因此,align-items 和 justify-content 在应用时需要针对不同的轴线进行设置。
那么,如何判断应该使用 align-items 还是 justify-content 呢?这需要根据具体布局及需求进行考虑。
如果我们希望让元素在纵向上对齐、水平方向上均匀分布,则可以使用 align-items: center 和 justify-content: space-around 来实现:
<div class="container"> <div class="item item1"></div> <div class="item item2"></div> <div class="item item3"></div> </div>
// www.javascriptcn.com code example
.container {
display: flex;
flex-direction: column;
height: 400px;
align-items: center;
justify-content: space-around;
}
.item {
width: 100px;
height: 100px;
}
.item1 {
background-color: red;
}
.item2 {
background-color: blue;
}
.item3 {
background-color: green;
}上面的代码中,我们使用了 flex-direction: column 来让元素在纵向上排列。然后,使用 align-items: center 来让元素在纵向上居中对齐,使用 justify-content: space-around 来让元素在水平方向上均匀分布。结果如下:

结语
本文对 CSS Flexbox 布局中的 align-items 和 justify-content 进行了详细的介绍,包括区别、用法以及示例代码。希望能够帮助读者更好地理解并使用 CSS Flexbox 布局。在实际使用时,需要结合具体需求进行灵活应用,从而实现更加丰富多样的布局效果。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/67c804cae46428fe9eddc7c7