CitizenInsane CitizenInsane - 1 month ago 5
CSS Question

Text centering in a 1cm x 1cm cell

I want to create a table with 3 cells. Second cell must be centered and 1cm width by 1 cm height. Text in second cell must be horizontally/vertically centered:

I almost succeeded but even after many attempts I absolutely fail to have the text to appear in the middle of the second cell:



<table>
<tr>
<td style="width:50%;"></td>
<td style="min-width:1cm;max-width:1cm;border:none">
<div style="min-height:1cm;max-height:1cm;background-color:red">
<span class="PageNumber">1</span>
</div>
</td>
<td style="width:50%;"></td>
</tr>
</table>





How can I have the
span
to occupy full
div
container in order to have centered text (vertical & horizontal) ?

NB: The real-code is more complex and I have just extracted the part that causes troubles (centering text in a 1x1 cm cell).

Answer

Aside from the fact that tables should only be used for tabular data, you can achieve what you want using display:flex:

.number {
  display: flex;
  min-height: 1cm;
  max-height: 1cm;
  background-color: red;
  align-items: center;
  justify-content: center;
}
<table>
  <tr>
    <td style="width:50%;"></td>
    <td style="min-width:1cm;max-width:1cm;border:none">
      <div class="number">
        1
      </div>
    </td>
    <td style="width:50%;"></td>
  </tr>
</table>

Comments