Formatting tables with css

Home

Contents

A simple example

Basic HTML Table Structure

CSS Styling Essentials

Responsive Table Tip (Optional)

Making tables responsive to PC and Mobile screens

Wrap the Table in a Scrollable Container

Use Relative Units for Widths

Add the Viewport Meta Tag

Optimize Font Sizes and Spacing

Optional: Stack Table Rows on Mobile

Test Across Devices

 

Formatting tables with css

A simple example

Basic HTML Table Structure

<table>

  <thead>

    <tr>

      <th>Item</th>

      <th>Quantity</th>

      <th>Price</th>

    </tr>

  </thead>

  <tbody>

    <tr>

      <td>Tea</td>

      <td>2</td>

      <td>$10</td>

    </tr>

    <tr>

      <td>Coffee</td>

      <td>1</td>

      <td>$12</td>

    </tr>

  </tbody>

</table>

CSS Styling Essentials

table {

  width: 100%;

  border-collapse: collapse;

  font-family: Arial, sans-serif;

}

th, td {

  padding: 12px;

  text-align: left;

  border-bottom: 1px solid #ccc;

}

 

thead {

  background-color: #f4f4f4;

}

 

tr:hover {

  background-color: #f9f9f9;

}

Responsive Table Tip (Optional)

For mobile-friendly design, consider wrapping your table in a scrollable container

CSS

.table-container {

  overflow-x: auto;

}

HTML

<div class="table-container">

  <table>...</table>

</div>

Making tables responsive to PC and Mobile screens

Wrap the Table in a Scrollable Container

This ensures horizontal scrolling on small screens without breaking layout.

HTML

<div class="table-container">

  <table>

    <!-- your table content -->

  </table>

</div>

CSS

.table-container {

  width: 100%;

  overflow-x: auto;

}

Use Relative Units for Widths

Avoid fixed pixel widths. Use percentages or em units so the table scales with screen size

table {

  width: 100%;

}

th, td {

  padding: 1em;

}

Add the Viewport Meta Tag

This tells mobile browsers to scale the page properly.

<meta name="viewport" content="width=device-width, initial-scale=1.0">

Place this in the of your HTML document.

Optimize Font Sizes and Spacing

Use media queries to adjust styles for smaller screens.

CSS

@media (max-width: 600px) {

  th, td {

    padding: 0.5em;

    font-size: 0.9em;

  }

}

Optional: Stack Table Rows on Mobile

For complex tables, you can use JavaScript or CSS tricks to stack rows vertically. But for simpler tables, horizontal scroll is usually cleaner and easier to implement.

Test Across Devices

§  Resize your browser window to simulate different screen sizes.

§  Use browser dev tools to emulate mobile views.

§  Test on actual devices when possible (PC, Mac, phone, tablet).