【发布时间】:2020-09-07 09:03:07
【问题描述】:
是否可以将单个元素与 flex 容器方向对齐?例如;我有一个容器,除了第一个元素应该左对齐之外,所有元素都应该右对齐。
是否可以使用'flex'而不是float来实现?在下面的例子中;如何顶部对齐第一个元素(在红色 div 中)和左对齐第一个元素(在绿色 div 中)?
.h-left {
align-self: flex-start;
}
.h-center {
align-self: center;
}
.h-right {
align-self: flex-end;
}
.v-top {
justify-self: flex-start;
}
.v-center {
justify-self: center;
}
.v-bottom {
justify-self: flex-end;
}
.container {
display: flex;
flex-direction: column;
}
.container.h-left {
align-items: flex-start;
}
.container.h-center {
align-items: center;
}
.container.h-right {
align-items: flex-end;
}
.container.v-top {
justify-content: flex-start;
}
.container.v-center {
justify-content: center;
}
.container.v-bottom {
justify-content: flex-end;
}
.h-container {
flex-direction: row;
}
.h-container.h-left {
justify-content: flex-start;
}
.h-container.h-center {
justify-content: center;
}
.h-container.h-right {
justify-content: flex-end;
}
.h-container.v-top {
align-items: flex-start;
}
.h-container.v-center {
align-items: center;
}
.h-container.v-bottom {
align-items: flex-end;
}
.container > * {
max-width: 150px;
}
<h4>The first element should be top aligned</h4>
<div class="container h-right v-bottom" style="background-color: red; height: 300px;">
<p class="h-top">This should be top aligned</p>
<p>This should be bottom aligned</p>
<p>This should be bottom aligned</p>
</div>
<h4>The first element should be left aligned</h4>
<div class="container h-container h-right v-bottom" style="background-color: green; height: 150px;">
<p class="h-left">This should be left aligned</p>
<p>This should be right aligned</p>
<p>This should be right aligned</p>
</div>
【问题讨论】: