CSS Tables

CSS allows you to style tables to make them more visually appealing and easier to read. You can adjust various aspects of tables, including borders, spacing, alignment, and more.

Styling Tables

Tables can be styled using several CSS properties, including border, padding, text-align, background-color, and more.

Table Properties

  • border - Defines the border of the table, rows, and cells.
  • padding - Adds space inside the cells.
  • text-align - Aligns text within table cells.
  • background-color - Sets the background color for table elements.
  • border-collapse - Specifies whether table borders should collapse into a single border.
  • width - Sets the width of the table.

Syntax

The basic syntax for styling tables is:


/* Table Styling */
table {
    border-collapse: collapse; /* Collapses table borders into a single border */
    width: 100%;
}

th, td {
    border: 1px solid #ddd; /* Adds border to table headers and cells */
    padding: 8px; /* Adds padding inside cells */
    text-align: left; /* Aligns text to the left */
}

th {
    background-color: #f4f4f4; /* Sets background color for table headers */
}

tr:nth-child(even) {
    background-color: #f9f9f9; /* Sets background color for even rows */
}

        

Examples

Example 1: Basic Table


/* Basic Table Styling */
table {
    border-collapse: collapse;
    width: 100%;
}

th, td {
    border: 1px solid #ddd;
    padding: 8px;
    text-align: left;
}

th {
    background-color: #f4f4f4;
}

tr:nth-child(even) {
    background-color: #f9f9f9;
}

            
Header 1 Header 2 Header 3
Data 1 Data 2 Data 3
Data 4 Data 5 Data 6

Example 2: Table with Borders


/* Table with Borders */
table {
    border-collapse: separate;
    border-spacing: 0;
}

th, td {
    border: 2px solid #000;
    padding: 12px;
}

thead {
    background-color: #e0e0e0;
}

            
Header A Header B Header C
Data A1 Data B1 Data C1
Data A2 Data B2 Data C2

Example 3: Styled Table Rows


/* Styled Table Rows */
tbody tr:nth-child(odd) {
    background-color: #f2f2f2;
}

tbody tr:hover {
    background-color: #ddd;
}

            
Column 1 Column 2 Column 3
Row 1 Data 1 Row 1 Data 2 Row 1 Data 3
Row 2 Data 1 Row 2 Data 2 Row 2 Data 3
Row 3 Data 1 Row 3 Data 2 Row 3 Data 3