使用flexbox对齐2个div:一个中心和另一个底部中心

时间:2016-05-05 13:49:39

标签: css flexbox

我正在尝试使用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>
&#13;
&#13;
&#13;

看起来差不多了,但是第一个盒子左对齐,而底部是右对齐。

有人可以帮忙吗?

修改:这与将我的标记为重复时引用的问题不同:该问题是询问如何使div与中心div等距离和底部。我正在询问如何将底部div放在容器的底部。

1 个答案:

答案 0 :(得分:2)

您可以更改为flex-direction: column,然后您可以使用边距来定位divs

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>