Idan Shechter Idan Shechter - 4 months ago 15
CSS Question

Responsive table with equal width and height TDs

How can I create a responsive HTML table that each cell/TD has equal width and height? So when I resize the browser window or resize the table's container, the table will resize, but each cell will have equal height and width.

Foundation doesn't take care of that. When I initialize the TD with fixed width and height in pixels, when resize the width of the browser, it shrinks the td horizontally, but doesn't keep the same aspect ratio.

I am using Foundation as my my base responsive framework.

Answer

Below is a way of doing it that will work .

https://jsfiddle.net/ocp36uLb/32/

table {
    border-collapse: collapse;
    width: 100%;
}
td {
    width: 50%;
    padding-bottom: 50%;
    display: inline-block;
}

By setting the padding to be the same as the width we create a square that maintains it's aspect ratio on resize. We also need to use display: inline-block; to override the default display: table-cell; which will make a cell expand to fit it's parent table. border-collapse: collapse; is also important as it overrides any table related border rendering.

However, this method may well be a pixel out at some sizes due to the way tables render. It works perfectly for divs (which you could use instead, I'm guessing) - even without the border-collapse definition.

Another way which will work perfectly for tables is to use vw units. A bit more complex as they take there size from the viewport, so you'll need to consider what proportion of the viewport your overall table size is. 1vw is 1% of the viewport. You'll see from the link that it's perfect.

table {
    width: 100%;
    border-collapse: collapse;
}
td {
    height: 15vw;
    width: 15vw;
    display: inline-block;
}

vw units are not so well supported yet (old IEs, some mobile browsers) so it would probably be worth using a fallback.

Comments