javascript - 使用 flexbox 将多个 DIV 居中并分层

标签 javascript html css flexbox

我想将多个 DIV 层叠在一起,同时使用 flexbox 将它们垂直和水平居中。

在下面的示例中,我希望 .whitebox.bluebox 在容器内垂直和水平居中,彼此重叠。目前 .whitebox 是用绝对位置定位的。这可能吗?

.container {
  height: 16px;
  width: 16px;
  background-color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  overflow: hidden;
  position: relative;
}

.bluebox {
  height: 16px;
  width: 16px;
  background-color: #0073FF;
  border-radius: 4px;
  position: absolute;
  top: 0;
  left: 0;
}

.whitebox {
  height: 8px;
  width: 8px;
  background-color: white;
  border-radius: 4px;
  position: absolute;
  top: 0;
  left: 0;
}
<div class="container">
  <div class="bluebox"></div>
  <div class="whitebox"></div>
</div>

最佳答案

无需定位 topleft。仅仅应用绝对定位就足够了,因为这会将元素“弹出”到它们自己的层中,因此它们可以随意放置而不会影响该层中的其他元素。一旦你这样做了,align-itemsjustify-content 就会完成它们的工作。

.container {
  height: 16px;
  width: 16px;
  background-color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  overflow: hidden;
  position: relative;
}

.bluebox {
  height: 16px;
  width: 16px;
  background-color: #0073FF;
  border-radius: 4px;
  position: absolute;

}

.whitebox {
  height: 8px;
  width: 8px;
  background-color: white;
  border-radius: 4px;
  position: absolute;

}

.border {
  height: 16px;
  width: 16px;
  border-radius: 4px;
  box-shadow: inset 0 0 0 1px rgba(0,0,0,0.1);
  position: absolute;
  top: 0;
  left: 0;
}
<div class="container">
  <div class="bluebox"></div>
  <div class="whitebox"></div>
  <div class="border"></div>
</div>

关于javascript - 使用 flexbox 将多个 DIV 居中并分层,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48412077/

相关文章:

javascript - 我怎么知道最后一次异步何时完成?

html - 如何在IE6-8中使用HTML5标签和css3?

html - 每个设备屏幕中元素的大小一致

html - 展开窗口时按钮位置发生变化

c# - 使用 CSS 定位标题文本

javascript - 节点列表中 for 的意外行为

javascript - file.match(regex) 与提供的文件名不匹配

php - 在 jQuery 中设置?

html - 为页面的主容器提供最大宽度

javascript - meteor 设计模板