css - 如何将一个元素与 flexbox 对齐?

标签 css alignment flexbox

https://jsfiddle.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;
}

最佳答案

要将一个 flex 子元素右对齐,请将其设置为margin-left: auto;

来自flex spec :

One use of auto margins in the main axis is to separate flex items into distinct "groups". The following example shows how to use this to reproduce a common UI pattern - a single bar of actions with some aligned on the left and others aligned on the right.

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

Updated fiddle

.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>

注意:

您可以通过在中间的 flex 元素上设置 flex-grow:1(或简写 flex:1)来实现类似的效果,这会将最后一个元素一直推到右边。 ( Demo )

然而,明显的区别是中间项变得比它可能需要的更大。为 flex 元素添加边框以查看差异。

Demo

.wrap {
  display: flex;
  background: #ccc;
  width: 100%;
  justify-content: space-between;
}
.wrap div {
  border: 3px solid tomato;
}
.margin div:last-child {
  margin-left: auto;
}
.grow div:nth-child(2) {
  flex: 1;
}
.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 margin">
  <div>One</div>
  <div>Two</div>
  <div>Three</div>
</div>

<div class="wrap grow">
  <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 - 如何将一个元素与 flexbox 对齐?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35269947/

相关文章:

html - 如何使用 flexbox 填充网格

javascript - Bootstrap 4 导航下拉列表问题

html - 导航栏和 iframe 之间的空白

java - GUI 文本对齐

html - Flex 容器获取高度错误的 Safari

html - 如何使用 Flex 垂直中心和视口(viewport)单位 vh?

CSS 嵌套注释

javascript - 我如何根据复选框的状态更改另一种已具有自己样式表的媒体类型的 CSS 值?

CSS 菜单右对齐问题

css - 在 HTML 中对齐表格