csstext-alignmenttablecellvertical-text

How do I horizontally align vertical text in a table with CSS?


I have some writing-mode: vertical-rl text in a table cell. By default, it gets pushed to the left side of the cell, but I want to center it or push it right. If I were handling horizontal-tb text, I would use text-align: center or vertical-align but there doesn't seem to be a corresponding horizontal-align property.

In this example, I want the vertical text centered in the cell:

Vertical text is pushed left, but I want it centered

I am testing this in Firefox 91.

Here is a jsfiddle for the above image: https://jsfiddle.net/a965ej2x/

And the corresponding code:

<table>
<tbody>
  <tr>
    <th>This is my heading</th>
  </tr>
  <td>
    しょうがない
  </td>
</tbody>
</table>

CSS:

td {
  writing-mode: vertical-rl;
  text-align: center;
  vertical-align: middle;
}
td, th {
  border: 1px solid black;
}

Solution

  • It seems to be a bug on Firefox that you can fix by adding an extra element where you apply the writing-mode

    td {
      text-align: center;
    }
    
    td span {
      writing-mode: vertical-rl;
      vertical-align:top; /* remove bottom whitespace */
    }
    
    td,
    th {
      border: 1px solid black;
    }
    <table>
      <tbody>
        <tr>
          <th>This is my heading</th>
        </tr>
        <td>
          <span>しょうがない</span>
        </td>
      </tbody>
    </table>