css - 在 flex 容器的剩余空间(不是全宽)中水平居中 flex 元素

标签 css alignment flexbox

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

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

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

解决方案:我有一个新的 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.

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

另一种方法是删除第一个 flex 元素 (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/

关于css - 在 flex 容器的剩余空间(不是全宽)中水平居中 flex 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33519065/

相关文章:

html - CSS html 图像放置

javascript - 如何使用 jquery 显示具有相同 id 的多个 div 之一?

javascript - 我如何将 css 高度与浏览器窗口的大小对齐?

html - 悬停转换 CSS 中的抖动

javascript - 单元格的动态宽度 React Native

html - Bootstrap 按钮仅在 ios safari 和 ios chrome 上具有奇怪的行为

javascript - 如何在 React Native 中使按钮居中

css - 在 div 中居中固定图像

html - CSS flexbox 破坏行为

html - 如何在 IE 中书写彩色 Unicode 表情符号