htmlcss

vertical-align: middle misaligns normal text and a


I have some text with a link in a table, which I'm trying to align vertically:

* {
    vertical-align: middle;
}
<table>
  <tr>
    <td>
      Shoul be <a href="https://www.google.com">aligned</a> vertically
    </td>
    <td>
      <div>Multiple</div>
      <div>lines</div>
    </td>
    <td>
      <span>Could be </span><a href="https://www.google.com">aligned</a><span> with spans</span>
    </td>
  </tr>
</table>

But as you can see, the first "aligned" isn't aligned with the rest of the text (or maybe the other way around).

The only fix I could find was to wrap all text in spans, but is there a way to do it without all the extra spans?

Thanks!


Solution

  • The easiest solution is to not use * because you will apply vertical-align to everything when you only need it on the td element.

    td {
        vertical-align: middle;
    }
    <table>
      <tr>
        <td>
          Should be <a href="https://www.google.com">aligned</a> vertically
        </td>
        <td>
          <div>Multiple</div>
          <div>lines</div>
        </td>
        <td>
          <span>Could be </span><a href="https://www.google.com">aligned</a><span> with spans</span>
        </td>
      </tr>
    </table>

    The issue is that when having a with span all of them will get aligned the same thus they will be at the same position but when you align the a inside a text you will move it slightly from the baseline (default alignment) to the middle which create the issue.

    If you align only the a and not the span you will have the same issue as the first case like shown below.

    Hover to notice how the border will get misaligned

    td {
        vertical-align: middle;
    }
    
    span,a {
     border:1px solid;
    }
    
    table:hover a {
        vertical-align: middle;
    }
    <table>
      <tr>
        <td>
          Shoul be <a href="https://www.google.com">aligned</a> vertically
        </td>
        <td>
          <div>Multiple</div>
          <div>lines</div>
        </td>
        <td>
          <span>Could be </span><a href="https://www.google.com">aligned</a><span> with spans</span>
        </td>
      </tr>
    </table>