提问者:小点点

如何将一个项目与FlexBox对齐?


https://jsfidle.net/vhem8scs/

是否可以用FlexBox将两个项目左对齐,一个项目右对齐?链接更清楚地表明了这一点。最后一个例子是我想要实现的。

在flexbox中,我有一个代码块。对于float,我有四个代码块。这是我更喜欢FlexBox的一个原因。

HTML

<div class="wrap">
  <div>One</div>
  <div>Two</div>
  <div>Three</div>
</div>

<!-- DESIRED RESULT -->

<div class="result">
  <div>One</div>
  <div>Two</div>
  <div>Three</div>
</div>

CSS

.wrap {
  display: flex;
  background: #ccc;
  width: 100%;
  justify-content: space-between;
}

.result {
  background: #ccc;
  margin-top: 20px;
}

.result:after {
  content: '';
  display: table;
  clear: both;
}

.result div {
  float: left;
}
.result div:last-child {
  float: right;
}

共1个答案

匿名用户

若要将一个flex子级向右对齐,请使用margin-left:auto;设置该子级

根据flex规范:

主轴线中的自动边距的一个用途是将弹性项目分成不同的“组”。下面的示例演示了如何使用它来再现一个通用的UI模式--单个操作条,其中一些在左侧对齐,其他在右侧对齐。

.wrap div:last-child {
  margin-left: auto;
}

null

.wrap {
  display: flex;
  background: #ccc;
  width: 100%;
  justify-content: space-between;
}
.wrap div:last-child {
  margin-left: auto;
}
.result {
  background: #ccc;
  margin-top: 20px;
}
.result:after {
  content: '';
  display: table;
  clear: both;
}
.result div {
  float: left;
}
.result div:last-child {
  float: right;
}
<div class="wrap">
  <div>One</div>
  <div>Two</div>
  <div>Three</div>
</div>

<!-- DESIRED RESULT -->
<div class="result">
  <div>One</div>
  <div>Two</div>
  <div>Three</div>
</div>