如何左右对齐 flexbox 列?

How to align flexbox columns left and right?

对于典型的 CSS,我可以将两列中的一列向左浮动,另一列向右浮动,中间有一些间距 space。我如何使用 flexbox 做到这一点?

http://jsfiddle.net/1sp9jd32/

#container {
  width: 500px;
  border: solid 1px #000;
  display: -webkit-flex;
  display: -ms-flexbox;
  display: flex;
}
#a {
  width: 20%;
  border: solid 1px #000;
}
#b {
  width: 20%;
  border: solid 1px #000;
  height: 200px;
}
<div id="container">
  <div id="a">
    a
  </div>
  <div id="b">
    b
  </div>
</div>

您可以将 justify-content: space-between 添加到父元素。这样做时,子 flexbox 项目将对齐到相对的边,它们之间有 space。

Updated Example

#container {
    width: 500px;
    border: solid 1px #000;
    display: flex;
    justify-content: space-between;
}

#container {
    width: 500px;
    border: solid 1px #000;
    display: flex;
    justify-content: space-between;
}

#a {
    width: 20%;
    border: solid 1px #000;
}

#b {
    width: 20%;
    border: solid 1px #000;
    height: 200px;
}
<div id="container">
    <div id="a">
        a
    </div>
    <div id="b">
        b
    </div>
</div>


您还可以将 margin-left: auto 添加到第二个元素以使其右对齐。

Updated Example

#b {
    width: 20%;
    border: solid 1px #000;
    height: 200px;
    margin-left: auto;
}

#container {
    width: 500px;
    border: solid 1px #000;
    display: flex;
}

#a {
    width: 20%;
    border: solid 1px #000;
    margin-right: auto;
}

#b {
    width: 20%;
    border: solid 1px #000;
    height: 200px;
    margin-left: auto;
}
<div id="container">
    <div id="a">
        a
    </div>
    <div id="b">
        b
    </div>
</div>

我想出了 4 种方法来实现结果。这里是demo

方法一:

#a {
    margin-right: auto;
}

方法二:

#a {
    flex-grow: 1;
}

方法三:

#b {
    margin-left: auto;
}

方法四:

#container {
    justify-content: space-between;
}

有不同的方法,但最简单的方法是使用 space-between 请参阅最后的示例

#container {    
    border: solid 1px #000;
    display: flex;    
    flex-direction: row;
    justify-content: space-between;
    padding: 10px;
    height: 50px;
}

.item {
    width: 20%;
    border: solid 1px #000;
    text-align: center;
}

see the example

另一种选择是在要填充剩余 space.

的标签之间添加另一个具有 flex: auto 样式的标签

https://jsfiddle.net/tsey5qu4/

HTML:

<div class="parent">
  <div class="left">Left</div>
  <div class="fill-remaining-space"></div>
  <div class="right">Right</div>
</div>

CSS:

.fill-remaining-space {
  flex: auto;
}

这相当于 flex: 1 1 auto,吸收沿主轴的任何额外 space。

除了 Jost 的回答之外,如果您也需要垂直对齐,请根据需要使用 align-items: center;

#container {
    width: 500px;
    border: solid 1px #000;
    display: flex;
    justify-content: space-between;
    align-items: center;
}