How to Create a Responsive Table in CSS

Creating a responsive table in CSS can be a bit tricky, but with the right techniques, it can be done easily.

In this CSS tutorial, we’ll go over the steps to create a responsive table that looks great on both desktop and mobile devices.

First, let’s define what we mean by a “responsive table.”

Essentially, a responsive table is one that adjusts to the size of the screen it’s being viewed on.

This means that on a larger screen, the table will be displayed in its full size, with all columns and rows visible.

On a smaller screen, such as a mobile device, the table will adjust so that it’s still easy to read and navigate.

There are a few different ways to create a responsive table in CSS, but one of the most popular is to use media queries.

Media queries allow you to apply different styles to a website or web page depending on the screen size.

To create a responsive table, we’ll use a media query to change the way the table is displayed on smaller screens.

Here’s an example of a basic table:

<table>
  <tr>
    <th>Header 1</th>
    <th>Header 2</th>
    <th>Header 3</th>
  </tr>
  <tr>
    <td>Row 1, Cell 1</td>
    <td>Row 1, Cell 2</td>
    <td>Row 1, Cell 3</td>
  </tr>
  <tr>
    <td>Row 2, Cell 1</td>
    <td>Row 2, Cell 2</td>
    <td>Row 2, Cell 3</td>
  </tr>
</table>

To make this table responsive, we’ll use a media query to change the way the table is displayed on screens smaller than a certain width.

Here’s an example of a media query that changes the table’s display when the screen width is less than 600 pixels:

@media (max-width: 600px) {
  table {
    width: 100%;
    display: block;
  }
  th {
    display: none;
  }
  td {
    display: block;
    border: none;
    margin-bottom: 10px;
  }
}

This media query changes the table’s width to 100%, which makes it take up the full width of the screen.

It also changes the display property of the table’s header and data cells.

By setting the display property of the header cells to “none”, we’re hiding them on smaller screens.

And by setting the display property of the data cells to “block”, we’re making sure that each data cell takes up the full width of the screen.

Additionally, we can add some css to make it more readable and beautiful.

For example, we can make the rows alternate in color, add some padding and margin, etc.

table {
    border-collapse: collapse;
    width: 100%;
}
th, td {
    padding: 10px;
    text-align: left;
}
th {
    background-color: #f2f2f2;
}
tr:nth-child(even){background-color: #f2f2f2}

With these simple CSS changes, our table is now fully responsive and will look great on any screen size.