在宽度受限的父元素内水平居中没有设置宽度的子元素

Horizontally centering a child element with no set width inside a parent with a constrained width

我有一组 div 作为标记。在标记的脚下我有数字。我想将这些数字居中,但到目前为止的挑战是在 div 内进行,宽度限制为 4px。

我设法通过显式地给 span 标签设置宽度,将它们定位 left: 50%,负值 margin-left: -20px(其宽度的一半)和最后 text-align: center 来实现这一点。虽然它有效,但它似乎有点 hacky 因为如果数字在跨度之外中断,则水平对齐不起作用。

.parent {
    background: black;
    display: inline-block;
    margin: 0 30px;
    position: relative;
    height: 20px;
    width: 4px;
}

.child {
    text-align: center;
    position: absolute;
    bottom: -20px;
    left: 50%;
    margin-left: -20px;
    width: 40px;
}
<div class="parent">
    <span class="child">1</span>
</div>

<div class="parent">
    <span class="child">10</span>
</div>

<div class="parent">
    <span class="child">100</span>
</div>

<div class="parent">
    <span class="child">10000000</span>
</div>

在 child 上使用 CSS3 transform 将其恢复为自身宽度的 50%。

.child {
    text-align: center;
    position: absolute;
    top: 100%;
    left: 50%;
    transform:translateX(-50%);

}

.parent {
  background: black;
  display: inline-block;
  margin: 0 30px;
  position: relative;
  height: 20px;
  width: 4px;
}
.child {
  text-align: center;
  position: absolute;
  top: 100%;
  left: 50%;
  transform: translateX(-50%);
}
<div class="parent">
  <span class="child">1</span>
</div>

<div class="parent">
  <span class="child">10</span>
</div>

<div class="parent">
  <span class="child">100</span>
</div>

<div class="parent">
  <span class="child">10000000</span>
</div>

支持 IE9 及更高版本 - CanIUse.com

您可以将 child 代码设为:

.child {
    text-align: center;
    position: absolute;
    bottom: -20px;
    left: 50%;
    -webkit-transform: translateX(-50%);
  -ms-transform: translateX(-50%);
  transform: translateX(-50%);
}

这将使您的数字居中。问题是它只适用于现代浏览器。

JSFIDDLE