我正在使用 flex box 将两个元素与容器的左右对齐,同时将它们垂直居中对齐。这是我要实现的目标的一个非常简单的示例。
HTML:
<div class="container">
<div class="first"></div>
<div class="second"></div>
</div>
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;
}
如果屏幕足够宽以在一行中容纳两个内部 div,则此方法非常有效。但是,当屏幕尺寸较小(例如手机)并且 div 换行到第二行时,第二行也会与左侧对齐(即 flex-start
)。如何强制第二个 div 始终与右边框对齐,无论它是在第一行还是包裹在第二行?
编辑: 在示例中,我为两个子元素分配了固定宽度 - 这只是为了简单起见。在实际应用程序中,所有宽度都根据运行时从数据库中读取的内容动态变化。因此,任何基于固定大小的解决方案都行不通。
最佳答案
您可以尝试添加一些左边距以将 .second
元素推到右侧:
.second {
margin-left: auto;
}
.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;
}
<div class="container">
<div class="first"></div>
<div class="second"></div>
</div>
或者,类似地,将所有元素向右对齐,但将 .first
元素推向左侧:
.container {
justify-content: flex-end;
}
.first {
margin-right: auto;
}
.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;
}
<div class="container">
<div class="first"></div>
<div class="second"></div>
</div>
关于html - Flexbox wrap - 最后一行的不同对齐方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26983602/