How to Build a Stylish, Responsive HTML Table


In this tutorial, we’ll learn how to build a stylish table and modify its layout to adapt to various screen sizes. 

The data presented in our table will come from the IMDb platform and list a few of Steven Spielberg’s movies.

Responsive Tables in HTML

Tabular data should be structured in one way: with the HTML table elements. This is the semantically correct approach, but it can give us some serious stylistic challenges. Tables are notoriously inflexible where responsive layouts are concerned.

There are several solutions to the issue: scrollable containers wrapping the table, collapsible cells, using different (less semantic) markup. We’re going to use Flexbox to display our table cells in a grid layout on smaller screens.

1. Begin With the HTML Markup

The markup will be straightforward: a table with six rows inside a container.

Here’s how it’ll look:

Notice the visible@l and hidden@l classes. These will help us toggle specific elements depending on the viewport size.

2. Add Styles

Mostly, we’ll follow a mobile-first approach for our styles. As mentioned above, we’ll need two helper classes:

At any point, our table will have zebra-striped rows; we’ll use the :nth-child() CSS pseudo-class to generate them.

On small and medium screens, the table header will be hidden. At this point, we’ll show a number indicating the movie number. We’ll replace the table headings with some strong elements that will appear inside each cell.

So, on small screens, it will look like this:

The table appearance on small screensThe table appearance on small screensThe table appearance on small screens

On medium screens, the table will be a two-column grid:

The table appearance on medium screensThe table appearance on medium screensThe table appearance on medium screens

On large screens, all table cells will have a width of 25%. Plus, the table headings will become visible.

The table appearance on large screensThe table appearance on large screensThe table appearance on large screens

Each time we hover over a row, an associated image will appear. Also, a small black bullet will sit at the center-right position to indicate the active row.

How it looks a hovered table row on large screensHow it looks a hovered table row on large screensHow it looks a hovered table row on large screens

With all the above in mind, here’s a part of those styles. Notice how we begin with our table rows using display: flex; flex-wrap: wrap;, with display: table-row; kicking in once we hit the 1000px breakpoint:

You can check them all by clicking on the CSS tab of the demo.

Conclusion

In this short tutorial, we covered a way to make a responsive table that will look great on different screens. On small and medium screens, we make it behave like a grid, whereas on larger screens, we have a typical table with cells.

Here’s a reminder of what we built:

As always, thanks a lot for reading!



Source link