我正在尝试使用 Flexbox 将其父级中的两个 div 对齐,一个完全居中,另一个底部居中。他们都共享相同的父级 div。结果应该是这样的:
------------------------
| |
| |
| |
| |
| ------ |
| | b1 | |
| | | |
| ------ |
| |
| ------ |
| | b2 | |
| ------ |
------------------------
这是我到目前为止所拥有的:
div {
box-sizing: border-box;
border: 1px black solid;
}
.text-center{
text-align:center;
}
.flex-wrap {
width:400px;
height: 400px;
background: #ddd;
display: flex;
align-items: flex-start;
}
.flex-centered {
align-self: center;
}
.flex-bottom-center {
align-self: flex-end;
}
<div class="flex-wrap">
<div class="flex-centered text-center">
Here is some text for the center
</div>
<div class="flex-bottom-center text-center">
Here is some text for the bottom center
</div>
</div>
看起来差不多了,但第一个框左对齐,而底部右对齐。
有人可以帮忙吗?
编辑:这与将我的标记为重复时引用的问题不同:该问题询问如何制作底部 div
到中心等距div
和底部。我的问题是如何放置底部div
在容器的底部。
最佳答案
您可以更改为flex-direction: column
,然后可以使用边距来定位div
div {
box-sizing: border-box;
border: 1px black solid;
}
.text-center{
text-align:center;
}
.flex-wrap {
width:400px;
height: 400px;
background: #ddd;
display: flex;
justify-content: center;
flex-direction: column;
align-items: center;
}
.flex-centered, .flex-bottom-center {
margin-top: auto;
}
<div class="flex-wrap">
<div class="flex-centered text-center">Here is some text for the center</div>
<div class="flex-bottom-center text-center">Here is some text for the bottom center</div>
</div>
如果要将 .flex-centered
定位在父元素的垂直中心,则需要使用 position:absolute
将其从元素流中删除
div {
box-sizing: border-box;
border: 1px black solid;
}
.text-center {
text-align: center;
}
.flex-wrap {
width: 400px;
height: 400px;
background: #ddd;
display: flex;
justify-content: flex-end;
flex-direction: column;
position: relative;
align-items: center;
}
.flex-centered {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
<div class="flex-wrap">
<div class="flex-centered text-center">Here is some text for the center</div>
<div class="flex-bottom-center text-center">Here is some text for the bottom center</div>
</div>
关于css - 使用flexbox对齐2个div : one center-center and the other bottom center,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37052378/