【问题标题】:One-line text not aligned to center of div单行文本未与 div 中心对齐
【发布时间】:2016-05-12 13:02:46
【问题描述】:

对于具有多行标题的 div,文本与中心完美对齐。然而,对于单行标题,情况并非如此(即使 text-align 设置为 center)。文本将自身与父跨度的左边框对齐。看起来绝对是微不足道的,但还没有成功。

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>

【问题讨论】:

  • 你想水平居中对齐吗?
  • 首先如果你使用 display: table-cell 父级必须有 display: table

标签: html css text-align


【解决方案1】:

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

主要更改是使父显示:表并为子跨度提供 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>

【讨论】:

    【解决方案2】:

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

    这是一个简单的修复!

    当使用display table-cell时,父元素必须display table

    注意:默认span元素是display inline

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

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

    此外,您的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>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-08-04
      • 2018-02-02
      • 1970-01-01
      • 2014-07-09
      • 1970-01-01
      • 1970-01-01
      • 2022-09-23
      相关资源
      最近更新 更多