I'm try to build a table such that
- All cells have the same size and square shape.
- Cell size is independent from the cell content.
- Cell content is horizontally and vertically centered in the cell.
For example, see the following image
I edited the code found here Make table cells square to obtain an output similar to the previous image.
body { font-size: 1.5em; }
table {
width: 180px; /* fixed table width */
margin: auto;
border-collapse: collapse;
}
td, th {
width: 33%; /* each cell has 1/3 of the total width */
position: relative;
border: 1px solid;
text-align: center; /* content is horizontally centered */
}
th { background: yellow; }
td:before, th:before {
content: '';
display: block;
margin-top: 30%; /* attempt to center the content vertically */
}
td:after, th:after {
content: '';
display: block;
margin-top: 100%; /* set the height of the cell */
}
td div, th div {
position: absolute;
left: 0;
right: 0;
}
th div { color: red; }
<table>
<tr>
<th><div>+</div></th>
<th><div>0</div></th>
<th><div>1</div></th>
</tr><tr>
<th><div>0</div></th>
<td><div>0</div></td>
<td><div>1</div></td>
</tr><tr>
<th><div>1</div></th>
<td><div>1</div></td>
<td><div>10</div></td>
</tr>
</table>
The result is quite similar to the previous image, but if the either the table width
or the font-size
are changed, then the vertical centering is messed up.
I think the only problem is the verical centering. As you can see from the code I made an attempt to center the content vertically by manually setting margin-top: 30%
. But this value needs to be changed accordingly to the table width
and the font-size
.
Is it possible to automatically center the content vertically?