Learn CSS3 to style your web pages

Know what is CSS, its uses and how to add? CSS Style for Text, Paragraphs, Tables, Links and Forms. Background image with CSS, Borders styles in CSS, Set margin and positions in CSS, etc.

CSS Tables


Table Borders

To specify table borders in CSS, use the border property.

The example below specifies a black border for <table>, <th>, and <td> elements:

See this example:

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

Notice that the table in the example above has double borders. This is because both the table and the and elements have separate borders.


Collapse Table Borders

The border-collapse property sets whether the table borders should be collapsed into a single border:

See this example:

table {
    border-collapse: collapse;
}

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

Table Width and Height

Width and height of a table are defined by the width and height properties.

The example below sets the width of the table to 100%, and the height of the <th> elements to 50px:

See this example:

table {
    width: 100%;
}

th {
    height: 50px;
}

Horizontal Alignment

The text-align property sets the horizontal alignment (like left, right, or center) of the content in <th> or <td>.

By default, the content of <th> elements are center-aligned and the content of <td> elements are left-aligned.

The following example left-aligns the text in <th> elements:

See this example:

th {
text-align: left;
}

Vertical Alignment

The vertical-align property sets the vertical alignment (like top, bottom, or middle) of the content in <th> or <td>.

By default, the vertical alignment of the content in a table is middle (for both <th> and <td> elements).

The following example sets the vertical text alignment to bottom for <td> elements:

See this example:

td {
    height: 50px;
    vertical-align: bottom;
}

Table Padding

To control the space between the border and the content in a table, use the padding property on <td> and <th> elements:

See this example:

th, td {
    padding: 15px;
    text-align: left;
}

Hoverable Table

Use the :hover selector on <tr> to highlight table rows on mouse over:

See this example:

tr:hover {background-color: #f5f5f5}

Responsive Table

A responsive table will display a horizontal scroll bar if the screen is too small to display the full content

Add a container element (like <div>) with overflow-x:auto around the <table> element to make it responsive

See this example:

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

<table>
... table content ...
</table>

</div>