如何将大字符置于较小容器的中心?

How to center a large character over a smaller container?

我正在尝试使用 CSS 在比字符窄的 span 中使单个字符居中。

我有:

<span id="A">X</span><span id="B">Y</span><span id="C">Z</span>

所有三个跨度都有

display: inline-block;
width: 32px;
height: 32px;

并且中间跨度中的 Y 字符大于跨度本身。我希望角色在跨度上居中,同时与 X 和 Z 重叠。

当 Y 小于跨度时,以下规则适用于居中:

vertical-align: middle;
text-align: center;

当 Y 比包含框宽时,这不再有效:Y 现在向右移动。当 Y 比包含框宽时,如何水平居中?

(我曾尝试使用其他答案中建议的 display: table-cell,但这失败了,因为当时 width: 32px 被忽略了。)

这是我尝试过的:https://jsfiddle.net/seehuhn/hec3xucu/

span {
  display: inline-block;
  width: 32px;
  height: 32px;
  font: bold 32px/32px courier;
  position: relative;
  vertical-align: middle;
  text-align: center;
}

#A {
  background: red;
}

#B {
  background: #8f8;
  font-size: 92px;
  color: #F99;
  z-index: 1;
}

#C {
  background: blue;
}
<p><span id="A">X</span><span id="B">Y</span><span id="C">Z</span>

你可以用 flex-box 做到这一点

  span {
    display: flex;
    display: -webkit-box;
    display: -webkit-flex;
    display: -ms-flexbox;
    justify-content: center;
    -webkit-justify-content: center;
    align-items: center;
    -webkit-align-items: center;
    width: 32px;
    height: 32px;
    font: bold 32px/32px courier;
    position: relative;
    float: left;
  }

  #A {
    background: red;
  }

  #B {
    background: #8f8;
    font-size: 92px;
    color: #F99;
    z-index: 1;
  }

  #C {
    background: blue;
  }

如果您想了解有关 flex-box 的更多信息,请单击 here

您绝对可以将 Y 放在其他 2 个之上。

p {
  position: relative;
  display: inline-block;
  background: #8f8;
}

span:not(#B) {
  display: inline-block;
  width: 32px;
  height: 32px;
  font: bold 32px/32px courier;
  position: relative;
  vertical-align: middle;
  text-align: center;
}

#A {
  background: red;
  margin-right: 32px;
}

#B {
  font-size: 92px;
  color: #F99;
  z-index: 1;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

#C {
  background: blue;
}
<p><span id="A">X</span><span id="B">Y</span><span id="C">Z</span>

居中 任何东西 使用 CSS flexbox 非常简单。

p {
  display: flex;               /* 1 */
}

span {
  width: 32px;
  height: 32px;
  text-align: center;
  font: bold 32px/32px courier;
}

#B {
  z-index: 1;
  font-size: 92px;
  color: #F99;
  background: #8f8;
  display: flex;               /* 2 */
  justify-content: center;     /* 3 */
}

#A {
  background: red;
}

#C {
  background: blue;
}
<p>
  <span id="A">X</span>
  <span id="B">Y</span>
  <span id="C">Z</span>
</p>

备注:

  1. 将主容器设为弹性容器。现在您可以在子元素上使用弹性对齐属性。另外,默认情况下,弹性容器会将所有子元素排成行。

  2. 使 #B 元素成为(嵌套的)弹性容器,这样您就可以将弹性属性应用于内容(从技术上讲,它在 HTML 结构中向下三层) .

  3. 使用 flex 属性使内容水平居中。 (如果您需要垂直居中,请添加 align-items: center。)