Creating Responsive Tables

Tutorial 5 of 5

Introduction

In this tutorial, we are going to learn how to create responsive tables that can adapt to different screen sizes, an essential feature for a mobile-friendly website.

You will learn:
- How to create tables using HTML and CSS.
- How to make these tables responsive using media queries.
- Tips for optimizing your table's design for better usability.

Prerequisites:
- Basic knowledge of HTML
- Basic knowledge of CSS

Step-by-Step Guide

Understanding Tables in HTML

Tables in HTML can be created using the <table> tag. To create rows and data cells in the table, we use <tr> and <td> tags respectively.

Making Tables Responsive with CSS

We can make our tables responsive by using CSS media queries, which allow us to apply different styles depending on the screen size.

Code Examples

Basic HTML Table

Here is a basic HTML table:

<table>
  <tr>
    <td>Row 1, Cell 1</td>
    <td>Row 1, Cell 2</td>
  </tr>
  <tr>
    <td>Row 2, Cell 1</td>
    <td>Row 2, Cell 2</td>
  </tr>
</table>

This would create a table with two rows and two cells in each row.

Making the Table Responsive

To make the table responsive, we will use the CSS overflow property, which specifies what should happen if content overflows an element's box, and media queries.

.table-responsive {
  width: 100%;
  overflow-x: auto;
}

@media screen and (max-width: 600px) {
  .table-responsive table {
    width: 100%;
  }
  .table-responsive td {
    word-wrap: break-word;
  }
}

In the above CSS, we first make the table width 100% and set overflow-x property to auto which will add a horizontal scroll bar when the content is too wide. Then, we add a media query for screens with a maximum width of 600px. For these screen sizes, we ensure the table width is 100% and words in the data cells break and wrap to the next line if they are too long.

Summary

In this tutorial, we learned how to create tables in HTML and make them responsive using CSS. The key points covered include:

  • Creating tables in HTML using <table>, <tr>, and <td> tags.
  • Making tables responsive using CSS overflow property and media queries.

Practice Exercises

  1. Create a table with 5 rows and 3 cells in each row.
  2. Make the table responsive for screens with a maximum width of 800px.

Solutions

  1. Creating a table with 5 rows and 3 cells in each row.
<table>
  <tr>
    <td>Row 1, Cell 1</td>
    <td>Row 1, Cell 2</td>
    <td>Row 1, Cell 3</td>
  </tr>
  <!-- Add more rows here -->
</table>
  1. Making the table responsive for screens with a maximum width of 800px.
.table-responsive {
  width: 100%;
  overflow-x: auto;
}

@media screen and (max-width: 800px) {
  .table-responsive table {
    width: 100%;
  }
  .table-responsive td {
    word-wrap: break-word;
  }
}

For further practice, you can experiment with different table styles and layouts, and try making them responsive for different screen sizes.