将跨度定位在其他跨度之上,并在 div 中水平居中,高度可变

Position span on top of other span and center both horizontally in div w/ variable height

我有一个安静简单的 html 结构,但我无法弄清楚我必须做什么才能将 8 放在 0 的顶部而不丢失包装的高度 div。

如果我在两个跨度上使用浮动或绝对位置,divs 高度将减少为 0。如果我在第二个 div 上使用绝对位置和浮动的组合,我无法设法将跨度在容器中水平居中。

我希望你能告诉我我做错了什么,以及如何将第二个跨度移动到第一个跨度之上,同时让第一个跨度确定环绕的高度 div.

#wrapper {
  position: relative;
  width: 100%;
  text-align: center;
}

#first {
}

#first {
}
<div id="wrapper">
   <span id="first">0</span>
   <span id="second">8</span>
</div>

您可以通过组合使用 left: 50% 和否定 transform 来居中绝对定位的元素,这将允许您将 8 元素居中在 0:

之上

#wrapper {
  position: relative;
  width: 100%;
  height: auto;
  text-align: center;
}

#first, #second {
  color: white;
  display: block;
}

#first {
  background: blue;
  height: 50px;
  padding: 30px
}

#second {
  background: red;
  height: 10px;
  padding: 10px;
  position: absolute;
  top: 0;
  left:50%;
  transform: translateX(-50%);
}
<div id="wrapper">
   <span id="first">0</span>
   <span id="second">8</span>
</div>