【问题标题】:Spacing between flex elements?弹性元素之间的间距?
【发布时间】:2017-01-16 02:26:55
【问题描述】:

JSFiddle

我有一个用 flex 显示的列表:

<ul>
    <li></li>
    ....

ul{
  list-style-type: none;
  display: flex;
  flex-wrap: wrap;
  background: gold;
}

li{
    flex-basis: 25%;
    background:grey;
 }

现在我想在我的 li 元素之间留一些空间,添加边距或填充将元素推到下一行(当我有超过 4 个元素时,我想要 flex wrap)。

我知道上面的问题可以通过盒子大小来解决,但我的主要问题是我想要元素之间的间距,但第一个和最后一个元素要对齐父元素的左侧和右侧。

如何做到这一点?

例如。

|li|spacing|li|spacing|li|spacing|li|

【问题讨论】:

标签: html css flexbox


【解决方案1】:

检查一下 - 我使用 calc 调整 flex-basis 以允许自定义 margins,您可以为 ul 分配(使用 justify-content: space-between 分配保证金)。

ul {
  list-style-type: none;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  background: gold;
  margin: 10px;
  padding: 0;
  height: 100px;
}
li {
  flex-basis: calc(25% - 20px);
  background: grey;
}
<ul>
  <li></li>
  <li></li>
  <li></li>
  <li></li>
</ul>

让我知道您对此的反馈。谢谢!

【讨论】:

  • Pete - 我认为它已通过编辑空格之间的关系来修复。这看起来不错,谢谢!
  • 我会做的。
  • 太棒了——这很有帮助!
  • 请注意,“据报道,IE 和 Edge 不支持 'flex' 内的计算。” -- calc() @ caniuse.com
  • li 数未知怎么办。让我们说 2 或 5。我们如何才能均匀地固定空间?
【解决方案2】:

一个更简单的解决方案(在通用用例中):

假设您有 2 个元素,如下所示:

您可以使用以下 css 来获得元素之间的相同间距。

示例:

.elem1 {
    display: flex;
    flex-wrap: wrap;
    margin-left: 8px;
    margin-top: 8px;
}

.elem2 {
    margin-right: 8px;
    margin-bottom: 8px;
}
    <div class="elem1">
        <div class="elem2">1</div>
        <div class="elem2">2</div>
        <div class="elem2">3</div>
        <div class="elem2">4</div>
    </div>

这样可以在外边框上以及元素之间(在 x 或 y 方向上)实现相同的间距,而无需任何额外的计算。虽然justify-content: space-betweenjustify-content: space-around 可以产生类似的效果,但它也会使所有内容居中。

React 示例(使用 Material UI)

render() {
    return (
        <Box display="flex" flexWrap="wrap" ml={1} mt={1} >
            {this.service.items().map(element =>
                <Box key={element.id} mr={1} mb={1} >
                    <Card entity={element} />
                </Box>
            )}
        </Box>
    )
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-04
    • 2014-06-19
    • 1970-01-01
    • 2011-03-17
    • 1970-01-01
    • 1970-01-01
    • 2017-08-20
    • 2019-11-22
    相关资源
    最近更新 更多