CSS: Display Table on Small Screen

By Xah Lee. Date: . Last updated: .

Problem Description

You want a HTML: Table that can be displayed on a small screen e.g. mobile phone.

(The technique is called “responsive table”)

Here is how a table looks on laptop screen.

html table wide screen 2018-11-09 f9ff9
html table wide screen

On a small screen, it looks like this:

html table small screen 2018-11-09 f0c4a
html table small screen

With CSS, you can make it to look like this:

html table responsive design 2018-11-09 143d9
html table responsive design

Sample Table Code

Here is a sample HTML table to play with.

DecOctHexCharComment
6510141ASomething something long text here. Too long and is a problem when displaying on a small screen. And it is really long, so long that on small narrow width screen one column becomes long strip while other columns are empty space, and page becomes very long, requiring lots scroll.
6610242BSomething something long text here. Too long and is a problem when displaying on a small screen. And it is really long, so long that on small narrow width screen one column becomes long strip while other columns are empty space, and page becomes very long, requiring lots scroll.

Here is html code for the table.

<table class="nrm">
<tr><th>Dec</th><th>Oct</th><th>Hex</th><th>Char</th><th>Comment</th></tr>
<tr><td>65</td><td>101</td><td>41</td><td>A</td><td>Something something long text here. Too long and is a problem when displaying on a small screen. And it is really long, so long that on small narrow width screen one column becomes long strip while other columns are empty space, and page becomes very long, requiring lots scroll.</td></tr>
<tr><td>66</td><td>102</td><td>42</td><td>B</td><td>Something something long text here. Too long and is a problem when displaying on a small screen. And it is really long, so long that on small narrow width screen one column becomes long strip while other columns are empty space, and page becomes very long, requiring lots scroll.</td></tr>
</table>

Here is the CSS:

table {
border-collapse:collapse;
margin:1rem;
}
table th, table td {
padding:.25rem;
border:solid thin gray;
}
table th {
background-color:#d7e4f2;
}

Solution, CSS Responsive Table

Here is the CSS to change the look of table on small screen.

@media all and (max-width: 760px)
{

table {
display: block;
}

table caption {
display: inline-block;
}

table tr {
display: list-item;
border: none;
border-top: solid thin red;
}

table th {
display: inline-block;
border: solid thin gray;
margin-right: 0.2rem;
}

table td {
display: inline-block;
border: solid thin gray;
margin-right: 0.2rem;
}

}

CSS, Advanced