在 flex 容器的剩余 space(不是全宽)中水平居中一个 flex 项目

Horizontally center a flex item in remaining space (not full width) of flex container

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

这是我的 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>

我有一些 fiddle 给你:https://jsfiddle.net/msLd7g5j/1/

编辑:请注意,这不是重复项,至少不是您指出的副本,因为我希望左侧项目以 space 为中心,即 'left over' 而不是绝对居中。

解决方案:我得到了一个新的fiddle:https://jsfiddle.net/msLd7g5j/2/

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

`<span> </span>`

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

所以你想要:

...the right item on the right side and the left item centered to the space which is left.

...the left item centered to the space which is 'left over' and not centered absolutely.

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

另一种方法是删除第一个弹性项目 (display: none)。将中间弹性项目的内容包裹在 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/