Search code examples
htmlcss

Make CSS `text-align:center` Ignore Some Text


Here is what I've tried:

table {
  width: 100%;
}

td {
  text-align: center;
}

td > h4 {
  display: inline
}
<table>
  <td>
    <h4>Hello</h4><sup>World</sup>
  </td>
</table>

Unfortunately, the browser centers both "Hello" and "World" together. How can I center ONLY "Hello" (but still have "World" follow it)?


Solution

  • Here is some very simple CSS:

    sup {
      display: inline-block;
      width: 0px;
    }
    

    The idea is to force a width of 0, but allow it to overflow. (You can't set a width on an inline element, so we use inline-block instead)

    You can see the full example in a snippet below:

    table {
      width: 100%;
    }
    
    td {
      text-align: center;
    }
    
    /* Relevant CSS */
    sup {
      display: inline-block;
      width: 0px;
    }
    <table>
      <tr>
        <td>
          <h4 style="display: inline;">Hello</h4><sup>World</sup>
        </td>
      </tr>
    </table>