SmartCodingTips

HTML Table Styling

By default, HTML tables are plain and lack design. You can enhance them using CSS to improve layout, readability, and user experience.

Default Table vs. Styled Table

Here's how a table looks without and with CSS styling:


<table>
  <tr>
    <th>Product</th>
    <th>Price</th>
  </tr>
  <tr>
    <td>Book</td>
    <td>$10</td>
  </tr>
</table>
            

Use CSS to enhance borders, spacing, and colors.

Basic CSS Table Styling

This example applies common styling rules to make tables more readable:


table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  padding: 12px;
  border: 1px solid #ccc;
  text-align: left;
}

th {
  background-color: #f3f4f6;
  color: #333;
}
            

Zebra Striping Rows

Alternating row colors improve readability:


tr:nth-child(even) {
  background-color: #f9fafb;
}
            

Hover Effects

Highlight a row when the mouse hovers over it:


tr:hover {
  background-color: #e5e7eb;
}
            

Responsive Table Design

Use the following style for tables on smaller screens:


table {
  overflow-x: auto;
  display: block;
}
            

Or wrap the table in a container:


<div style="overflow-x: auto;">
  <table>...</table>
</div>
            

Accessibility Tips

  • Always use <th> for headers.
  • Add scope="col" or scope="row" attributes to header cells.
  • Use descriptive <caption> tags for screen readers.