Tables in the past were greatly overused in CSS, as they were one of the only ways we could create a fancy page layout.
Today with Grid and Flexbox we can move tables back to the job they were intended to do: styling tables.
Let’s start from the HTML. This is a basic table:
<table>
<thead>
<tr>
<th scope="col">Name</th>
<th scope="col">Age</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">Flavio</th>
<td>36</td>
</tr>
<tr>
<th scope="row">Roger</th>
<td>7</td>
</tr>
</tbody>
</table>
By default it’s not very attractive. The browser provides some standard styles, and that’s it:
We can use CSS to style all the elements of the table, of course.
Let’s start with the border. A nice border can go a long way.
We can apply it on the table
element, and on the inner elements too, like th
and td
:
table, th, td {
border: 1px solid #333;
}
If we pair it with some margin, we get a nice result:
One common thing with tables is the ability to add a color to one row, and a different color to another row. This is possible using the :nth-child(odd)
or :nth-child(even)
selector:
tbody tr:nth-child(odd) {
background-color: #af47ff;
}
This gives us:
If you add border-collapse: collapse;
to the table element, all borders are collapsed into one:
Download my free CSS Handbook
More css tutorials:
- The Flexbox Guide
- CSS Grid Tutorial
- CSS Variables (Custom Properties)
- Introduction to PostCSS
- The CSS margin property
- How to center an element with CSS
- CSS System Fonts
- How to print your HTML with style
- An introductory guide to CSS Transitions
- A CSS Animations Tutorial
- Introduction to CSS
- The CSS Guide
- How to setup Tailwind with PurgeCSS and PostCSS
- The Tailwind Cheat Sheet
- How to continuously rotate an image using CSS
- Making a table responsive using CSS
- How to debug CSS by bisecting
- CSS Selectors
- CSS Cascade
- CSS Specificity
- CSS Attribute Selectors
- CSS Colors
- CSS Units
- CSS url()
- CSS Typography
- The CSS Box Model
- The CSS position property
- CSS Media Queries and Responsive Design
- CSS Feature Queries
- CSS Transforms
- How to style lists using CSS
- CSS Vendor Prefixes
- CSS Inheritance
- CSS Pseudo Classes
- CSS Pseudo Elements
- Styling HTML Tables with CSS
- The CSS Display property
- The CSS calc() function
- CSS Borders
- Importing a CSS file using @import
- CSS Error Handling
- CSS Filters
- CSS Box Sizing
- CSS Backgrounds
- CSS Comments
- CSS Fonts
- CSS Padding
- The CSS float property and clearing
- CSS Normalizing
- The CSS z-index property
- How to disable text selection using CSS
- How to put an item at the bottom of its container using CSS
- How to invert colors using CSS
- Responsive pre tags in CSS
- Responsive YouTube Video Embeds
- What are good CSS Breakpoint values for Responsive Design?
- How to align center in flexbox