如何将表格标题居中?

时间:2017-08-22 10:27:35

标签: html css html-table center caption

我在桌子上有一个很长的标题,并且希望它们都与彼此的中心对齐。

HTML:

<table>
  <caption>This is a very long caption.</caption>
  <tr>
    <td>1</td><td>2</td>
  </tr>
  <tr>
    <td>3</td><td>4</td>
  </tr>
</table>

CSS:

caption {
  white-space: nowrap;
}

https://codepen.io/anon/pen/RZyxzg

2 个答案:

答案 0 :(得分:1)

使用align-items:center

使用flexbox

table {
  display: flex;
  flex-direction: column;
  align-items: center;
  border: red solid
}
<table>
  <caption>This is a very long caption.</caption>
  <tr>
    <td>1</td>
    <td>2</td>
  </tr>
  <tr>
    <td>3</td>
    <td>4</td>
  </tr>
</table>

答案 1 :(得分:0)

已经 。使用text-align: center您可以提供边框,并看到 long 文本将扩展表格的整个宽度。 (另请参阅将width设置为table

时的行为

注意:这似乎不适用于Firefox - 使用white-space: nowrap时,表格不会像Chrome一样调整其宽度。

见下面的演示:

&#13;
&#13;
table {
  border-collapse: collapse;
}

caption {
  white-space: nowrap;
}

td {
  border: 1px solid;
  text-align: center;
}
&#13;
<table>
  <caption>This is a very long caption and even longer</caption>
  <tr>
    <td>1</td>
    <td>2</td>
  </tr>
  <tr>
    <td>3</td>
    <td>4</td>
  </tr>
</table>
&#13;
&#13;
&#13;