css - 使用flexbox对齐2个div : one center-center and the other bottom center

标签 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>

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

有人可以帮忙吗?

编辑:这与将我的标记为重复时引用的问题不同:该问题询问如何制作底部 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/

相关文章:

html - ASP.Net mvc 表单抛弃了我的 CSS

html - 悬停效果不起作用 : Div color is not changed when hovering over a <a> anchor tag

php - 在 jQuery uploadify 中,在用户的文件路径上传之前将图像显示为缩略图

jquery - CSS 背景变化之间的延迟

javascript - 用CSS实现加权灵活布局

html - IE11 嵌套 flexbox 问题与父表

css - 如何在 CSS/Bootstrap 中水平堆叠/对齐图像而不考虑方向?

html - 为什么关闭 1 像素边框会在固定位置标题和 Flex 增长的情况下产生 75 像素溢出?

ios - react native : Flex for ScrollView doesn't work

javascript - 根据用户点击向所有页面添加样式表