首页 > 解决方案 > 将 div 放置在带有 padding 的 flexbox 底部

问题描述

我有类似的东西:

.flex-container {
  display: flex;
  justify-content: center;
  padding: 5%;
  position: relative;
}

.box1 {
  position: absolute;
  bottom: 0;
  width: 100%;
  height: 100%;
}
<div class="flex-container">
  <div class="box1"></div>
  <div class="box2"></div>
</div>

我希望能够让 box2 保持在中心,同时将 box1 定位在 flex 容器的底部。问题是因为弹性容器有填充,底部只将它定位到填充结束的地方。另一个问题是当我给 box1 绝对定位时,box2 将重新定位自己以填充整个 flex 容器,因为 box1 不在流动范围内。

标签: htmlcssflexbox

解决方案


目前尚不清楚您到底要达到什么目标,但如果我做对了,这应该可以作为解决方案。

.flex-container {
  display: flex;
  justify-content: center;
  padding: 5%;
  position: relative;
  border: 3px solid black;
}

div {
  text-align: center; // not necessary
}

.box1 {
  position: absolute;
  bottom: 0;
  width: 100%;
  height: 20%;
  border: 1px solid green;
}

.box2 {
  border: 1px solid red;
  height: 20px;
  width: auto;
  padding: 5px;
}
<div class="flex-container">
  <div class="box1">box1</div>
  <div class="box2">box2</div>
</div>

编辑:如果您确实想使元素居中,则需要将其中一个boxbox2容器的填充添加为人工height或使用该calc()方法。


推荐阅读