Flexbox wrap - 最后一行的不同对齐方式

Ale*_*s G 8 html css flexbox

我正在使用柔性盒将两个物品对齐到容器的左侧和右侧,同时垂直居中对齐它们.这是我想要实现的一个非常简单的例子.

HTML:

<div class="container">
    <div class="first"></div>
    <div class="second"></div>
</div>
Run Code Online (Sandbox Code Playgroud)

CSS:

.container {
    width:100%;
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: space-between;
    align-items: center;
}

.first {
    background-color: yellow;
    width: 200px;
    height: 100px;
}

.second {
    background-color: blue;
    width: 200px;
    height: 100px;
}
Run Code Online (Sandbox Code Playgroud)

这是示例jsfiddle.

如果屏幕宽度足以适合一行的内部div,则效果非常好.然而,当屏幕尺寸较小(例如移动电话)并且div包裹在第二条线上时,第二条线也变得与左侧对齐(即flex-start).如何强制第二个div始终与右边界对齐,无论它是在第一行还是包裹在第二行?

编辑:在示例中,我为两个子元素分配了固定宽度 - 这只是为了简单起见.在现实生活中,所有宽度都是根据在运行时从数据库中读取的内容动态变化的.因此,任何基于固定大小的解决方案都不起作用.

Ori*_*iol 17

您可以尝试添加一些左边距以将.second元素向右推:

.second {
    margin-left: auto;
}
Run Code Online (Sandbox Code Playgroud)

.container {
  width:100%;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: space-between;
  align-items: center;
}
.first {
  background-color: yellow;
  width: 200px;
  height: 100px;
}
.second {
  background-color: blue;
  width: 200px;
  height: 100px;
  margin-left: auto;
}
Run Code Online (Sandbox Code Playgroud)
<div class="container">
  <div class="first"></div>
  <div class="second"></div>
</div>
Run Code Online (Sandbox Code Playgroud)

或者,同样地,将右边的所有元素对齐,但将.first元素向左推:

.container {
    justify-content: flex-end;
}
.first {
    margin-right: auto;
}
Run Code Online (Sandbox Code Playgroud)

.container {
  width:100%;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: flex-end;
  align-items: center;
}
.first {
  background-color: yellow;
  width: 200px;
  height: 100px;
  margin-right: auto;
}
.second {
  background-color: blue;
  width: 200px;
  height: 100px;
}
Run Code Online (Sandbox Code Playgroud)
<div class="container">
  <div class="first"></div>
  <div class="second"></div>
</div>
Run Code Online (Sandbox Code Playgroud)