One-line 文本未与 div 的中心对齐

One-line text not aligned to center of div

对于标题为 multi-line 的 div,文本完全居中对齐。然而,对于 single-line 标题,情况并非如此(即使 text-align 设置为居中)。文本将自身与 parent 范围的左边框对齐。看起来绝对微不足道,但还没有成功。

span.text-content {
  background: rgba(255,255,255,0.5);
  color: white;
  cursor: pointer;
  display: inline-block;
  height: 100%;
  left: 0;
  position: absolute;
  top: 0;
  width: 100%;
  opacity:0;
}

span.text-content span {
  display: table-cell;
  text-align: center;
  vertical-align: middle;
  color: #000;
  font-weight: 900;
  text-transform: uppercase;
  position:absolute;
  top: 45%;
}
<span class="text-content"><span>Post Title</span></span>

这是使用您的代码进行的修复(我更改了背景颜色和不透明度以便可以看到它)。

主要更改是使父显示:table 并为子跨度提供 100% 的宽度,以便您的文本对齐有效。

span.text-content {
  background-color: white;
  color: white;
  cursor: pointer;
  display: table;
  height: 100%;
  left: 0;
  position: absolute;
  top: 0;
  width: 100%;
}

span.text-content span {
  display: table-cell;
  width: 100%;
  text-align: center;
  vertical-align: middle;
  color: #000;
  font-weight: 900;
  text-transform: uppercase;
  position:absolute;
  top: 45%;
}
<span class="text-content"><span>Post Title</span></span>

织法: http://kodeweave.sourceforge.net/editor/#fe0c9da444a8df390c6242afa00f0bb3

这是一个简单的修复!

使用display table-cell the parent element must be display table时。

注意: 默认跨度元素为 display inline.

要使您的文本水平居中,您需要 text-align center(在本例中为 table-cell 的父级)。

此外,在这种情况下,您不需要将位置(或顶部)应用于 table-cell,因为使用 vertical-align middle 已经使您的文本在 table-cell.[=23= 上垂直居中]

此外,您的 span.text-content 资格过高,只需使用 .text-content 即可。

顺便说一句:我删除了 .text-content 上的不透明度,所以我可以看到文字。

.text-content {
  cursor: pointer;
  display: table;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(255, 255, 255, 0.5);
  color: white;
  text-align: center;
}

.text-content span {
  display: table-cell;
  vertical-align: middle;
  color: #000;
  font-weight: 900;
  text-transform: uppercase;
}
<span class="text-content">
  <span>Post Title</span>
</span>