HTML Table Width โ€“ A Complete Guide with Examples and Best Practices

What is the width Attribute in HTML Tables?

The width attribute in the <table> tag specifies the width of the table in pixels or as a percentage of the parent container. However, in HTML5, the width attribute is deprecated, and CSS should be used instead.

๐Ÿ”น Best Practice: Use CSS (width) for better compatibility and responsive design.

Step-by-Step Guide to Using width in HTML Tables

Step 1: Setting Table Width Using the width Attribute (Deprecated)

<table border="1" width="500">
    <tr>
        <td>Row 1, Cell 1</td>
        <td>Row 1, Cell 2</td>
    </tr>
</table>

๐Ÿ”น Output: The table will be 500 pixels wide, but this method is outdated.


Step 2: Using CSS to Set Table Width (Recommended)

<style>
    table {
        width: 500px;
        border: 1px solid black;
    }
</style>

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

๐Ÿ”น Best Practice: Using CSS is the modern and flexible way to set table width.


Step 3: Setting Table Width as a Percentage

<style>
    table {
        width: 80%; /* Table takes 80% of the parent container */
        border: 1px solid black;
    }
</style>

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

๐Ÿ”น Output: The table width will adjust dynamically based on the parent containerโ€™s width.

Controlling Column Width

You can control individual column widths using the <colgroup> tag or CSS.

Using colgroup to Define Column Widths

<table border="1">
    <colgroup>
        <col style="width: 70%;">
        <col style="width: 30%;">
    </colgroup>
    <tr>
        <td>Column 1 (70%)</td>
        <td>Column 2 (30%)</td>
    </tr>
</table>

๐Ÿ”น Output: The first column takes 70%, and the second column takes 30% of the table width.

Responsive Table Width for Mobile Devices

Using CSS for a Fully Responsive Table

ย 
<style>
    table {
        width: 100%; /* Full width on all devices */
        max-width: 800px; /* Maximum width */
        border-collapse: collapse;
    }
    th, td {
        border: 1px solid black;
        padding: 10px;
        text-align: center;
    }
</style>

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

Best Practice:

โœ… Use width: 100% for tables that adapt to different screen sizes.
โœ… Use max-width to prevent tables from becoming too wide on large screens.

Common Mistakes to Avoid

โŒ Using width inside <td> without defining column widths properly.
โœ… Use <colgroup> or CSS for better control.

โŒ Forgetting to set border-collapse: collapse; โ€“ this prevents double borders.

โŒ Using fixed widths (px) for responsive design โ€“ instead, use % for flexibility.