在 flexbox 中使用相对和绝对定位的垂直居中

Vertical centering with relative and absolute positioning in flexbox

我正在为我的 .box 使用 absoluterelative 定位,但如您所见,文本看起来不像是 top: 100%

谁能解释这是为什么?

比如为什么在指定 top: 100% 时文本(这里有一些文本)会溢出到子元素中?

.box {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  align-items: flex-start;
  height: 200px;
  margin: 0 auto;
  width: 90%;
  border: 1px solid red;
}
.child {
  position: relative;
  width: 100px;
  height: 100px;
  border: 1px solid orange;
}
.childschild {
  position: absolute;
  top: 100%;
  left: 50%;
  transform: translate(-50%, -50%);
}
<div class="box">
  <div class="child">
    <img src="dog1.jpg" alt="Picture of a dog" width="250" height="250">
    <div class="childschild">
      some text is going here
    </div>
  </div>
  <div class="child">dfd</div>
  <div class="child">dfd</div>
</div>

如果我理解正确,这可能对你有帮助..

尝试使用 margin-top: -10px;,它会将顶部的 space 缩小 10 像素。您也可以尝试 marign-leftmargin-rightmargin-bottom.

问题是因为在您的 transform 中,您正在将 -50% 应用于 Y 轴,这意味着将从 top:100% 中减去 50%,所以它将是你有没有说 top:50% 而没有 transform

如@Michael_B所述,您可以仅将变换应用于 X 轴并移除 Y 轴,或者您可以使用下面的代码 vertically/horizontally 将文本居中放置在盒子:

position: absolute;
top: 100%;
right: 0;
left: 0;
margin: auto

注意:我把你的img改成了background-img(可选)

.box {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  height: 200px;
  margin: 0 auto;
  width: 90%;
  border: 1px solid red;
}
.child {
  width: 100px;
  height: 100px;
  border: 1px solid orange;
}
.box > div:first-of-type {
  background: url("//dummyimage.com/100x100");
  position: relative
}
.box > div:first-of-type div {
  position: absolute;
  top: 100%;
  right: 0;
  left: 0;
  margin: auto;
  width: 50px;
  text-align:center;
  background:red
}
<div class="box">
  <div class="child">
    <div>some text is going here</div>
  </div>
  <div class="child">dfd</div>
  <div class="child">dfd</div>
</div>

.. why is the text ('some text is going here' text) spilling into the child element when 100% was specified?

因为您已将 transform 属性 应用于元素:

.childschild { transform: translate(-50%, -50%); }

这告诉元素沿 x 轴向后移动其宽度的 50%,沿 y 轴向后移动其高度的 50%。

所以首先你要告诉它是 top: 100%。然后你告诉它回溯其高度的 50%,这将它放回到 .child 元素上方。您可以删除 transform,它将按预期工作。

试试这个:transform: translateX(-50%); (demo)

可以在此处找到更完整的插图说明: