问题
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.
回答1:
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.
回答2:
That works well if you have no content in the <td>
. But with some content the padding is extra to the height of the content. see example below:
<table width="100%" border="0" cellspacing="0" cellpadding="0" style="width: 100%; border-collapse: collapse;">
<tbody>
<tr>
<td style="width: 100%; padding-bottom: 100%; background-color: #896464">Lorem ipsum dolor sit amet.</td>
</tr>
<tr>
<td style="width: 100%; padding-bottom: 100%; background-color: #20A034">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla vitae elit libero, a pharetra augue.</td>
</tr>
</tbody>
</table>
来源:https://stackoverflow.com/questions/30762478/responsive-table-with-equal-width-and-height-tds