CSS Tables

Home / CSS / CSS Tables

CSS Tables


CSS Tables:

CSS (Cascading Style Sheets) can be used to style HTML tables, allowing you to control their appearance, layout, and design. Here are some common CSS properties and techniques for styling tables:

Table Layout:

width: You can set the width of the table using this property, either in pixels, percentages, or other valid CSS units.

max-width and min-width: These properties can be used to control the maximum and minimum width of the table.


<style>
    table {
         width: 100%;
         max-width: 800px;
         }
  </style>


Borders:

border-collapse: This property controls how table borders collapse into one another. Setting it to "collapse" creates a single border around each cell, while "separate" (default) keeps them separate.

border-spacing: Adjusts the spacing between table cells when border-collapse is set to "separate".

 
<style>
    table {
           border-collapse: collapse;
           border-spacing: 10px;
         }
  </style>

Cell Padding and Margin:

padding: Adds space inside each table cell.

margin: Adds space outside each table cell.

 
<style>
    td, th {
            padding: 10px;
            margin: 5px;
           }
  </style>

Text Alignment:

text-align: This property can be used to align text within table cells.

vertical-align: It controls the vertical alignment of content within cells.

 
<style>
    th {
      text-align: left;
    }

    td {
      text-align: center;
      vertical-align: middle;
    }
  </style>

Table Header Styles:

You can target table headers (<th>) specifically to give them a distinct style.


<style>
    th {
      background-color: #f2f2f2;
      font-weight: bold;
    }
  </style>

Alternating Row Colors:

You can use the :nth-child() pseudo-class to apply styles to alternating rows.


 <style>
    tr:nth-child(even) {
      background-color: #f2f2f2;
    }
  </style>

Hover Effects:

To provide a hover effect for table rows or cells, use the :hover pseudo-class.

<style>
    tr:hover {
      background-color: #ccc;
    }
  </style>

Borders for Cells:

You can add borders to individual cells, rows, or columns by targeting them specifically.

<style>
    td {
        border: 1px solid #ccc;
       }
  </style>

Table Caption:

You can style the table caption (if used) by targeting the caption element.

<style>
    caption {
      font-size: 1.5em;
      font-weight: bold;
    }
  </style>

Responsive Tables:

For responsive design, consider setting a max-width on the table container, and make sure the table is horizontally scrollable when necessary.

<style>
    .table-container {
      max-width: 100%;
      overflow-x: auto;
    }
  </style>