htmlcssalignmentcenter-align

How to center element using tables without scrollbars?


I have table (only table on the page). It has one row and 1 cell in it.

I want to center contents of this cell vertically and horizontally on the page. I am doing this by such html and css.

HTML:

<table>
  <tr><td>keks</td></tr>
</table>

CSS:

html, body, table, tr, td {
  width: 100%;
  height: 100%;
}

td {
  text-align: center;
  vertical-align: middle;
}

But this approach adds scrollbars (both vertical and horizontal). How to remove scrollbars? If I remove them by scrollbar: hidden content of the cell would not be on the center of the page. It would be a bit lower and righter.

Also maybe my approach is not correct and I can achieve this without adding scrollbars and content would be on the middle.

Here is the example: https://jsfiddle.net/0tpL9o7e/


Solution

  • There are automatically defined margin values of the HTML. The scrollbar appears for this... you need to reset them first.

    * {
      margin:0;
      padding:0
    }
    
    table{
      width: 100vw;
      height: 100vh
    }
    
    td {
      text-align: center;
      vertical-align: middle;
    }
    <table>
      <tr><td>keks</td></tr>
    </table>