【问题标题】:How do I use display:flex and justify-content:space-between, where the flex-item gets centered if there is only one of them?如何使用 display:flex 和 justify-content:space-between,如果只有其中一个,flex-item 会居中?
【发布时间】:2014-12-12 12:40:12
【问题描述】:

我有一个div,即display: flex,其中包含未知数量的弹性项目。我想使用justify-content: space-between,但问题是当有 one 项时,它会向左侧移动,而我希望它向中心移动。有没有唯一的 CSS 解决方案?

#container {
    display: flex;
    justify-content: space-between;
}
<div id="container">
    <div class='flex-item'></div>
    ...n flex-items...
</div>

然后我把一些块元素放在那里(类名-.flex-items),由于justify-content: space-between,它使divs之间的空间均匀分布,所以最左边的div接触到左边框和最右边的div 触及右边框。它反应灵敏。我的问题是只有一个flex-item 时的默认行为是左对齐,但我希望它居中对齐。什么是纯 CSS 解决方案?

【问题讨论】:

    标签: html css flexbox


    【解决方案1】:

    你是这样做的:

    #container {
        display: flex;
        justify-content: space-between;
    }
    
    .flexItem:nth-child(1):nth-last-child(1) {
        margin: 0 auto;
    }
    

    【讨论】:

    • 酷,更好
    • @MaryMelody 你想发布答案吗?
    • 没关系,我所做的只是从您的答案中替换了:only-child 选择器。 :)
    猜你喜欢
    • 1970-01-01
    • 2020-07-03
    • 2021-06-17
    • 2018-05-12
    • 2015-11-19
    • 1970-01-01
    • 2021-09-11
    • 1970-01-01
    • 2018-12-30
    相关资源
    最近更新 更多