我设置了一个包含两个项目的弹性盒,这两个项目应该位于普通屏幕的左侧和右侧。
如果屏幕不够大,无法将两者并排显示,则应换行,但它们应居中而不是左对齐。
我尝试了不同的解决方案(例如在子项目上使用
margin: auto
),但即使在同一行中,它们也更靠近中心。
这是一个简化的示例:
.container {
display: flex;
align-items: flex-end;
flex-wrap: wrap;
justify-content: space-between;
border: 1px solid black;
margin-bottom: 25px;
}
.large {
width: 500px;
}
.small {
width: 175px;
}
.item {
width: 100px;
height: 100px;
background-color: blue;
margin: 25px 0px;
}
<div class="container large">
<div class="item"></div>
<div class="item"></div>
</div>
<div class="container small">
<div class="item"></div>
<div class="item"></div>
</div>
https://jsfiddle.net/SoWhy/zfx4ub8x/
第一个容器是预期的定位,第二个容器在较小的屏幕上模拟相同的容器,注意左对齐。
有没有一种方法可以定义弹性盒在包裹时以不同的方式对齐项目,或者我只能使用“@media screen”方法来做到这一点(这需要我设置一定的大小,因此如果项目的大小不灵活)项目发生变化)?
这可能不适用于您的情况,但值得一提的是
justify-content: space-between
和 justify-content: space-around
之间鲜为人知的区别。
来自 Flexbox 规范:
属性justify-content
属性沿主轴对齐弹性项目 Flex 容器的当前行。justify-content
有五个值适用于
justify-content
。这是其中两个:
space-between
Flex 项目均匀分布在队列中。
如果剩余可用空间为负数或者线上只有一个 Flex 项目,则该值与
相同。flex-start
这解释了为什么您的项目在包装上与
space-between
左对齐。
现在看
space-around
:
space-around
Flex 项目均匀分布在行中,空间大小减半 两端。
如果剩余可用空间为负数或者线上只有一个 Flex 项目,则该值与
相同。center
因此,要在换行上居中对齐弹性项目,请考虑使用
space-around
。
.container {
display: flex;
flex-wrap: wrap;
justify-content: space-around; /* ADJUSTMENT */
border: 1px solid black;
}
.item {
width: 200px;
height: 100px;
background-color: blue;
margin: 25px;
}
<div class="container">
<div class="item"></div>
<div class="item"></div>
</div>
现在可以通过将
justify-content
设置为 space-evenly
来完成此操作。然而,此选项尚未包含在 Flexbox 规范中。
.container {
display: flex;
align-items: flex-end;
flex-wrap: wrap;
justify-content: space-evenly;
border: 1px solid black;
margin-bottom: 25px;
}
.large {
width: 500px;
}
.small {
width: 175px;
}
.item {
width: 100px;
height: 100px;
background-color: blue;
margin: 25px 0px;
}
<div class="container large">
<div class="item"></div>
<div class="item"></div>
</div>
<div class="container small">
<div class="item"></div>
<div class="item"></div>
</div>
注意:您必须对不同的宽度使用媒体查询。
无法检测它何时使用 css3 包装。
如果您想将项目居中,请使用
display:inline-flex
和 justify-content: center;
到容器,使用 margin: 0 auto;
到类 item
.container {
display: flex;
align-items: flex-end;
flex-wrap: nowrap;
justify-content: space-between;
border: 1px solid black;
margin-bottom: 25px;
}
.item {
width: 100px;
height: 100px;
background-color: blue;
margin: 25px;
margin: 0 auto;
}
当容器尺寸小于 200px 时会换行。
如果您想将项目保留在单行中
flex-wrap: nowrap
- 这会强制弹性项目被迫保留在单行中。
所以
.container
的样式将如下所示。
.container {
display: flex;
align-items: flex-end;
flex-wrap: nowrap;
justify-content: space-between;
border: 1px solid black;
margin-bottom: 25px;
}