How to make table responsive?

QuestionsQuestions8 SkillsProHTML TablesOct, 22 2025
0103

To make a table responsive, you can use CSS techniques that allow the table to adapt to different screen sizes. Here are a few methods to achieve this:

Method 1: Using CSS overflow

You can wrap your table in a div with overflow-x: auto; to allow horizontal scrolling on smaller screens.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        .table-responsive {
            overflow-x: auto;
            margin: 20px 0;
        }
        table {
            width: 100%;
            border-collapse: collapse;
        }
        th, td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: left;
        }
    </style>
</head>
<body>

<div class="table-responsive">
    <table>
        <tr>
            <th>Header 1</th>
            <th>Header 2</th>
            <th>Header 3</th>
            <th>Header 4</th>
        </tr>
        <tr>
            <td>Row 1, Cell 1</td>
            <td>Row 1, Cell 2</td>
            <td>Row 1, Cell 3</td>
            <td>Row 1, Cell 4</td>
        </tr>
        <tr>
            <td>Row 2, Cell 1</td>
            <td>Row 2, Cell 2</td>
            <td>Row 2, Cell 3</td>
            <td>Row 2, Cell 4</td>
        </tr>
    </table>
</div>

</body>
</html>

Method 2: Using CSS Media Queries

You can adjust the table layout using media queries to change styles based on screen size.

@media (max-width: 600px) {
    table, thead, tbody, th, td, tr {
        display: block;
    }
    th {
        display: none; /* Hide headers on small screens */
    }
    td {
        text-align: right;
        position: relative;
        padding-left: 50%; /* Space for labels */
    }
    td::before {
        content: attr(data-label); /* Use data-label for headers */
        position: absolute;
        left: 0;
        width: 50%;
        padding-left: 10px;
        font-weight: bold;
        text-align: left;
    }
}

And modify your HTML to include data-label attributes in the td elements:

<tr>
    <td data-label="Header 1">Row 1, Cell 1</td>
    <td data-label="Header 2">Row 1, Cell 2</td>
    <td data-label="Header 3">Row 1, Cell 3</td>
    <td data-label="Header 4">Row 1, Cell 4</td>
</tr>

Method 3: Using Frameworks

You can also use CSS frameworks like Bootstrap, which have built-in classes for responsive tables. For example:

<table class="table table-responsive">
    ...
</table>

Choose the method that best fits your needs to ensure your table is user-friendly on all devices.

0 Comments

no data
Be the first to share your comment!