How to center element using tables without scrollbars?

991 Views Asked by At

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/

3

There are 3 best solutions below

0
Mordecai On BEST ANSWER

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>

1
AudioBubble On

Add overflow:hidden on html element:

html {
  overflow: hidden; 
}
0
Nikola On

I would just set margins to 0 on body element since that's what created your scrollbars.

You can also hide scrolls by setting overflow:hidden but that way you might prevent your users to see some content that comes in later.

Inside webkit based browsers you can actually hide scrollbars using ::-webkit-scrollbar { display: none; } while still being able to scroll, just without the bars showing.

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

body {
  margin: 0;
}

td {
  text-align: center;
  vertical-align: middle;
}
<table>
  <tr><td>keks</td></tr>
</table>