Tables in CSS

Tables in CSS

Tables in CSS

 

In CSS, you can style tables using various properties to make them more visually appealing and user-friendly. Here’s an example of how to style a basic HTML table using CSS:

HTML:

				
					<table>
  <thead>
    <tr>
      <th>Product</th>
      <th>Price</th>
      <th>Quantity</th>
      <th>Total</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Product 1</td>
      <td>$10</td>
      <td>2</td>
      <td>$20</td>
    </tr>
    <tr>
      <td>Product 2</td>
      <td>$15</td>
      <td>3</td>
      <td>$45</td>
    </tr>
  </tbody>
</table>

				
			

CSS:

				
					table {
  border-collapse: collapse;
  width: 100%;
}

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

th {
  background-color: #4CAF50;
  color: white;
}

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

				
			

This CSS applies the following styles to the table:

  • The border-collapse property sets the table border style to “collapse”, meaning adjacent borders will be merged into a single border.
  • The width property sets the width of the table to 100% of its container.
  • The text-align and padding properties apply to both th and td elements, setting the text alignment and adding padding to the cells.
  • The background-color and color properties apply to th elements only, setting the background color to a green shade and the text color to white.
  • The tr:nth-child(even) selector targets every even row and applies a light gray background color.

These are just a few examples of how to style tables in CSS. There are many other properties you can use to further customize tables, such as border styles, font sizes, and text colors.

Join To Get Our Newsletter
Spread the love