16 Jun 2018
CSS Responsive Tables
Tables can be tricky in responsive design, especially when there's multiple headings. Here are two examples on how to style them for every device.
One heading
With one heading, it's easier to make the cells drop below each other on mobile, since the heading doesn't have to shift anywhere to stay above its related content.
Re-size your browser to see how it works. The cells go full-width at 600 pixels, producing a nice one-column layout for mobile users.
Heading |
|
---|---|
8:00am – 5:00pm | Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet |
10:00am – 2:00pm | Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet |
4:00pm – 7:00pm | Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet |
4:00pm – 7:00pm | Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet |
The HTML
I start with basic HTML markup and add a class, "responsive-table" to the table tag. I also set the heading to span 2 columns, since our rows will be two columns.
The CSS
I make the table full width and collapse the borders. For better readability, I add a background colour to every even row (or odd depending on how you want to style it).
For mobile, make each td and th cell display block so that they sit below each other. Remove the td borders to create a nice separation of content. For IE9, float the td cells since there are issues with blocking.
@media (max-width: 600px) {
.responsive-table td, .responsive-table th {
display: block;
}
.responsive-table tr td {
width: 100%;
float: left\9; /* IE9 */
}
.responsive-table td {
border: none;
}
}
Multiple headings
When there's 2 or more headings, the display block method causes them to lose their position above their related content. Instead, we can overflow the table so that when the screen becomes smaller, a scrollbar appears.
For this to work in IE9, wrap the table in a class rather than add the class to the table.
Example
<div class="overflow-table">
<table class="responsive-table">
<tbody>
<tr>
<td></td>
</tr>
</tbody>
</table>
</div>
Resize your browser to see how it works. The scroll bar kicks in for mobile
Time |
Event |
Members |
Sponsors |
Awards |
---|---|---|---|---|
8:00am – 5:00pm | Lorem ipsum dolor sit amet Lorem ipsum | Lorem ipsum dolor sit amet Lorem ipsum | Lorem ipsum dolor sit amet Lorem ipsum | Lorem ipsum dolor sit amet Lorem ipsum |
10:00am – 2:00pm | Lorem ipsum dolor sit amet Lorem ipsum | Lorem ipsum dolor sit amet Lorem ipsum | Lorem ipsum dolor sit amet Lorem ipsum | Lorem ipsum dolor sit amet Lorem ipsum |
4:00pm – 7:00pm | Lorem ipsum dolor sit amet Lorem ipsum | Lorem ipsum dolor sit amet Lorem ipsum | Lorem ipsum dolor sit amet Lorem ipsum | Lorem ipsum dolor sit amet Lorem ipsum |
The CSS
Set the table to display block and overflow when it gets too small.
.overflow-table {
display: block;
overflow-x: auto;
}