Kalen Hourna
Kalen Hourna

Reputation: 13

Center HTML Table Cell Content

I want to create an HTML table and I want its cells to be clickable. I have achieved that however, I can't vertically align text to middle in the cell. vertical-align:middle seems not working.

Here is my code:

<style type="text/css">

td {
  width: 200px;
  border: solid 1px green;
  height: 100%;
  text-align: center;
  vertical-align: middle;

}
td a {
  display: inline-block;
  height:100%;
  width:100%;


}
td a:hover {
  background-color: yellow;
}
</style>   

<table>
  <tbody>
    <tr>
      <td>
        <a href="http://www.google.com/">Cell 1<br>
        second line</a>
      </td>
      <td>
        <a href="http://www.google.com/">Cell 2</a>
      </td>
      <td>
        <a href="http://www.google.com/">Cell 3</a>
      </td>
      <td>
        <a href="http://www.google.com/">Cell 4</a>
      </td>
    </tr>
  </tbody>
</table>

Can you help me with that?

Thank you!

Upvotes: 1

Views: 123

Answers (2)

Asons
Asons

Reputation: 87191

The simplest way is to add a span to the anchors text like this

td {
  width: 200px;
  border: 1px solid green;
  height: 100%;
  text-align: center;
  vertical-align: middle;
  position: relative;
}
td a {
  display: inline-block;
  width: 100%;
  height: 100%;
}
td a span {
  position: relative;
  display: inline-block;
  top: 50%;
  transform: translateY(-50%);
}
td a:hover {
  background-color: yellow;
}
<table>
  <tbody>
    <tr>
      <td>
        <a href="http://www.google.com/"><span>Cell 1<br>
        second line</span></a>
      </td>
      <td>
        <a href="http://www.google.com/"><span>Cell 2</span></a>
      </td>
      <td>
        <a href="http://www.google.com/"><span>Cell 3</span></a>
      </td>
      <td>
        <a href="http://www.google.com/"><span>Cell 4</span></a>
      </td>
    </tr>
  </tbody>
</table>

A more modern way to make a table, if you are able to alter the markup a little, would be like this.

.wrapper {
  display: table;
}
.wrapper a {
  display: table-cell;
  width: 200px;
  border: 1px solid green;
  height: 100%;
  text-align: center;
  vertical-align: middle;
}
.wrapper a:hover {
  background-color: yellow;
}
<div class="wrapper">
  <a href="http://www.google.com/">Cell 1<br>
    second line</a>
  <a href="http://www.google.com/">Cell 2</a>
  <a href="http://www.google.com/">Cell 3</a>
  <a href="http://www.google.com/">Cell 4</a>
</div>

Upvotes: 1

Ashish Patel
Ashish Patel

Reputation: 772

Use this for right solotion

    td {
    border: 1px solid green;
    display: table;
    float: left;
    height: 100%;
    text-align: center;
    vertical-align: middle;
    width: 200px;
}
td a {
    display: table-cell;
    float: none;
    height: 100%;
    text-align: center;
    vertical-align: middle;
    width: 100%;
}

Upvotes: 1

Related Questions