在一行中使用flexbox,left-align和right-align元素

问题描述 投票:16回答:2

在过去,我会使用两个容器,并使用clearfix向左浮动一个,另一个向右浮动。但我认为这种方法有点陈旧,现在可以很好地支持flex功能。

问题是我不知道如何使用flex来解决这个问题。

这是一个带有一些按钮的屏幕截图。辅助操作左对齐,其他两个主要操作应右对齐。

enter image description here

这是我的标记:

<footer>
    <button>Back</button>
    <span class="primary-btns">
        <button>Cancel</button>
        <button>Go</button>
    </span>
</footer>

有人能告诉我在这里应该使用什么CSS flex方法吗?

html css html5 css3 flexbox
2个回答
22
投票

你可以使用justify-content: space-between

footer {
  display: flex;
  justify-content: space-between;
}
<footer>
  <button>Back</button>
  <span class="primary-btns">
    <button>Cancel</button>
    <button>Go</button>
  </span>
</footer>

更新:你也可以在没有spanmargin-left: auto DEMO的情况下做到这一点


11
投票

在这种情况下,您甚至不需要嵌套容器。

现代CSS技术(flex和grid)使这种布局变得简单,只需要一个容器。

footer {
  display: flex;
}

button:first-child {
  margin-right: auto;
}

button {
  margin: 5px;
}
<footer>
  <button>Back</button>
  <button>Cancel</button>
  <button>Go</button>
</footer>

Flex自动边距消耗指定方向上的所有可用空间。

这也有效:

button:nth-child(2) { margin-left: auto }

关于汽车保证金的全部内容:Methods for Aligning Flex Items

© www.soinside.com 2019 - 2024. All rights reserved.