csshtml-tablevertical-alignmentcenteringtablecell

Table cell conundrum: trying to vertically center a link inside a table cell whose entire cell area is link-clickable


As you can see, in order to make the entire table cell link-clickable, I used td a {display: block}. The problem is td a {vertical-align: middle} no longer works with display: block. Not sure how else to center it vertically. Any help would be greatly appreciated.

P.S. I avoided using line-height because my link needs to be multi-line.

table {
width: 300px;
border-collapse: collapse;
}

td {
border: 1px solid #000000;
height: 100px;
vertical-align: middle;
}

td a {
display: block;
height: 100px;
vertical-align: middle !important;
}
<table>
<tr>
<td>TEXT</td>
<td><a href="">LINK</a></td>
</tr>
</table>


Solution

  • You can use an auxiliar span and center it inside the anchor, so its content is free to move and align.

    E.g.:

    table {
      width: 300px;
      border-collapse: collapse;
    }
    
    td {
      border: 1px solid #000000;
      height: 100px;
      vertical-align: middle;
    }
    
    td a {
      display: flex;
      height: 100%;
    }
    
    td a span {
      height: fit-content;
      align-self: center;
    }
    <table>
      <tr>
        <td>TEXT</td>
        <td>
          <a href="">
            <span>
              A VERY LONG LINK MAY BE LIKE THIS ONE, I GUES, RIGHT? HERE WE GO :D
            </span>
          </a>
        </td>
      </tr>
    </table>