CSS Tables

Although HTML provides some attributes to customize the table, with CSS one can greatly improve the styles and look of an HTML Table.

See Example of a CSS improved table below:

S/N Name Age Gender
1 Erisan Olasheni 19 Male
2 Adeolu Mayowa 17 Female
3 Deje Ayeola 21 Male
4 Kelly Wilford 16 Male
  Do It Yourself

We have some CSS properties used to customize the look of an HTML Table.

  • border
  • border-collapse
  • vertical-align
All other CSS properties can also work for the HTML Table.

Table Borders

To specify table borders in CSS, use the border property.
The example below specifies a white border for <table>, <th>, and <td> elements:

Example

table, th, td
{
border: 1px solid black;
}

  Do It Yourself

Can you observe that the table in the example above has double borders? This is because both the <table>, <th> and <td> elements have separate borders.

To display a single border for the table, use the border-collapse property.

Collapsing the Borders

The border-collapse property is used to set whether the table borders are collapsed into a single border or separated:

Example

table, th, td
{
border-collapse: collapse;
}

  Do It Yourself

Sizing the Table

The size of of a table (width and height) is specified by the width and height properties.
The example below sets the width of the table to 100%, and the height of its children elements to 50px

Example

table {
width: 100%;
} 

tr, td, th {
height: 50px;
}

  Do It Yourself

The example sets the height of the table cells to 50px

Table Spacing

The space between the table cells and its contents can be controlled using the padding property.

To specify a certain amount of space between the table cells and the contents, use the padding property on <th> and <td> elements.

Example

table th,table td {
  padding: 20px;
}

  Do It Yourself

Table Colors

The example below specifies the color of the borders and the text and background color of elements:

Example

table, td, th {
border: 1px solid green; 
}

th {
background-color: green; color: white; }

  Do It Yourself

What You Should Know at the End of This Lesson

  • You should be able to tell briefly what CSS Table Styling is all about.
  • You should be able to collapse the table borders to bring out a more improved look.
  • You should be able to specify an appropriate spacing between a table and its contents.