CSS Tables

A plain HTML table has no borders and looks cramped. A few CSS rules make it clean.


Borders and spacing

table { border-collapse: collapse; width: 100%; }
th, td { border: 1px solid #ccc; padding: 8px; text-align: left; }
th { background: #0073aa; color: #fff; }

border-collapse: collapse joins the borders of neighbour cells. Without it you see a double border.


Zebra stripes and hover

tr:nth-child(even) { background: #f2f2f2; }
tr:hover { background: #ddd; }
Result with zebra stripes (the hover colour does not show in this box)
Name City Marks
Robin Delhi 85
Maria Mumbai 92
John Pune 78
Asha Jaipur 88


Text alignment

td.number { text-align: right; }
th, td { vertical-align: middle; }

Responsive table

A wide table can break the layout of a small phone. Put it in a box that scrolls sideways.

.table-wrap { overflow-x: auto; }
<div class="table-wrap">
  <table>...</table>
</div>

Summary

  • Use border-collapse: collapse, padding and borders.
  • tr:nth-child(even) makes zebra stripes.
  • Wrap wide tables in an overflow-x: auto container.
  • Learn the HTML side in HTML Tables.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.