html - 单行文本未与 div 中心对齐

标签 html css text-align

对于多行标题的 div,文本与中心完美对齐。然而,对于单行标题,情况并非如此(即使文本对齐设置为居中)。文本将自身与父跨度的左边框对齐。看起来绝对微不足道,但未能做到正确。

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>

最佳答案

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

主要更改是让父级显示:表格并为子级提供 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>

关于html - 单行文本未与 div 中心对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37176211/

相关文章:

html - CSS - 三 Angular 形边框无法正确呈现 IE8

css - Wordpress 对齐按钮不起作用

html - 使用文本对齐使图像居中

html - 垂直移动 div 中的文本(文本对齐除外)

javascript - HTML 字段包含值时显示为空

php - chrome "net : Failed to load resource: net::ERR_SPDY_PROTOCOL_ERROR"有什么问题?

javascript - 我不想两次调用自定义函数

html - HTML 格式的母版页

html - 将文本对齐到 div 的中心,另一个 div 作为百分比背景

html - 响应式网站在移动设备上工作但不在构建中