【问题标题】:Horizontally center a flex item in remaining space (not full width) of flex container在弹性容器的剩余空间(不是全宽)中水平居中弹性项目
【发布时间】:2016-02-04 18:47:19
【问题描述】:

我有一个响应式设计,它连续包含 3 个项目。如果屏幕变小,第一个将被删除。所以这 3 个项目是用 flexbox 和justify-content:space-between 分配的,这使得外部项目绑定到侧面,中间项目居中。现在如果第一个项目被删除,我想成为右侧的右侧项目,左侧​​的项目以左侧的空间为中心。

这是我的 3 项代码:

<div style="display:flex;flex-flow:row;justify-content:space-between;align-items:center">
   <span style="width:70px;text-align:right">To the left</span> 
   <div style="height:40px;width:100px;background-color:red">Center</div>
   <span style="width:70px;text-align:right">To the right</span>    
</div>

这两个项目:

<div style="display:flex;flex-flow:row;justify-content:space-between;align-items:center">
   <div style="height:40px;width:100px;background-color:red">Center</div>
   <span style="width:70px;text-align:right">To the right</span>    
</div>

我为你准备了一些小提琴:https://jsfiddle.net/msLd7g5j/1/

编辑:请注意,这不是重复的,至少不是您指出的那个,因为我希望左侧项目居中于“剩余”而不是绝对居中的空间。

解决方案:我有一个新的小提琴:https://jsfiddle.net/msLd7g5j/2/

我只是不删除第三个元素,而是删除内容,所以元素看起来像

`<span> </span>`

flexbox 只是完成它的工作并将中间元素居中到相对中间,并设置justify-content:space-between

【问题讨论】:

    标签: css alignment flexbox


    【解决方案1】:

    所以你想要:

    ...右边的项目和左边的项目居中 剩下的空间。

    ...左边的项目以“剩余”的空间为中心,而不是 绝对居中。

    您的解决方案(发布在答案的底部)看起来不错。您从第一个 flex 项目中删除所有内容并将其设为零 width。使用justify-content: space-between,这会将第二个弹性项目居中在容器的左边缘和下一个元素的左边缘之间。这似乎工作得很好。

    另一种方法是删除第一个弹性项目 (display: none)。将中间 flex 项的内容包裹在 span 中。将所有内联样式从父级移动到子级。然后将width: 100%; text-align: center; 应用到父级。

    <div style="display:flex; flex-flow:row; justify-content:space-between;align-items:center">
        <span style="text-align:right; display: none;"> </span> 
        <div style="width: 100%; text-align: center;"><span style="display: inline-block;
                        width:100px; background-color:blue; height: 40px;">Center</span></div>
        <span style="width:70px;text-align:right">To the right</span>   
     </div>
    

    演示:https://jsfiddle.net/msLd7g5j/4/

    【讨论】:

    • 至于你总结了一切并给出了另一个解决方案,我标记你的解决方案:)
    猜你喜欢
    • 1970-01-01
    • 2016-01-22
    • 1970-01-01
    • 2020-12-30
    • 1970-01-01
    • 2017-05-29
    • 2018-02-21
    • 1970-01-01
    • 2022-01-09
    相关资源
    最近更新 更多