首页 > 解决方案 > 在设置为对齐的嵌套 div 中水平居中文本

问题描述

我正在尝试创建一个响应式网站(不使用 flex)。我需要在两个display:table单元格上创建一个标题,并且我希望它居中。持有表格的主要 div 是text-align:justify. 我似乎没有做任何修复它!

我已经尝试了几乎所有我能找到的关于这个主题的东西: text-align:center;

    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    margin: 0 auto;

以上只是简单margin: 0 auto; 的和众多的组合。文字顽固地留在右上角。

HTML

<div class="row">
  <div class="novel novelleft">
    <div class="noveltitle">TITLE</div>
      stuff
  </div>
  <div class="novel novelright">
      more stuff
  </div>
</div>

CSS

.novel {
  display: table;
  width: 100%;
  padding: 10px;
  text-align: justify;
  text-align-last:left;
  background-color: #fff;
}
.novelleft {
  width: 40%;
  display: table-cell;
  vertical-align: top;
  padding-left: 13%;
  background-color: #fff;
}
.novelright {
  width: 60%;
  display: table-cell;
  vertical-align: middle;
  padding-right: 13%;
  background-color: #fff;
}

.noveltitle {
  font-family: 'Cinzel', serif;
  text-align: center;
}

如果不对,我很抱歉,我是新来的。谢谢你的帮助!

编辑 这是它在做 什么我想要它做什么

标签: htmlcssnestedtext-align

解决方案


如果您想要一个带有居中标题的表格,只需使用带有居中标题的表格。

.novel {
  width: 100%;
  padding: 10px;
  background-color: #fff;
}
.novelleft {
  width: 40%;
  vertical-align: top;
  padding-left: 13%;
  background-color: #fff;
}
.novelright {
  width: 60%;
  vertical-align: middle;
  padding-right: 13%;
  background-color: #fff;
}

.noveltitle {
  font-family: 'Cinzel', serif;
  text-align: center;
}
<table class="novel">
 <caption class="noveltitle">TITLE</caption>
 <tr>
  <td class="novelleft">stuff</td>
  <td class="novelright">more stuff</td>
 </tr>
</table>

或者如果你不想使用 <table> 元素,你可以使用 use divs,但是你需要保持正确的表格结构:

.novel {
  display: table;
  width: 100%;
  padding: 10px;
  background-color: #fff;
}
.novelrow {
  display: table-row;
}
.novelleft {
  display: table-cell;
  width: 40%;
  vertical-align: top;
  padding-left: 13%;
  background-color: #fff;
}
.novelright {
  display: table-cell;
  width: 60%;
  vertical-align: middle;
  padding-right: 13%;
  background-color: #fff;
}

.noveltitle {
  display: table-caption;
  font-family: 'Cinzel', serif;
  text-align: center;
}
<div class="novel">
 <div class="noveltitle">TITLE</div>
 <div class="novelrow">
  <div class="novelleft">stuff</div>
  <div class="novelright">more stuff</div>
 </div>
</div>


推荐阅读