OneBite.Dev - Coding blog in a bite size

style table in css

Code snippet for how to style table in css with sample and detail explanation

Creating a stylish table using CSS not only enhances the aesthetics of your website but also makes it easy to read and navigate the contained data. By manipulating the table elements with CSS styles, you can easily change the look of your web page tables.

Code snippet: Styling a Table with CSS

Below is a simple example of how to style a table using CSS:

<!DOCTYPE html>
<html>
<head>
<style>
table {
  width: 100%;
  border-collapse: collapse;
}

table, td, th {
  border: 1px solid black;
  padding: 15px;
  text-align: center;
}

th {background-color: #f2f2f2;}
</style>
</head>

<body>

<table>
  <tr>
    <th>Name</th>
    <th>Age</th> 
    <th>Location</th>
  </tr>
  <tr>
    <td>Jane</td>
    <td>23</td>
    <td>New York</td>
  </tr>
</table>

</body>
</html>

Code Explanation for Styling a Table with CSS

This code demonstrates how to effectively style a HTML table using CSS. The table tag is used to create a table. The td tag creates standard cells in the table, and the th tag is used for header cells. The tr tag denotes a table row.

  • With width: 100%;, we are setting the table to take up the full width of its parent element for better visibility.

  • The CSS property border-collapse: collapse; is used to collapse the border lines into a single line for a cleaner look.

  • We also use border: 1px solid black; to add a border of 1px thickness, which will be solid black, around our table, td, and th.

  • Padding: 15px; is for spacing around the contents of the td and th to allow for some white space around the text.

  • text-align: center; is used to centrally align the text in the td and th.

  • Lastly, th {background-color: #f2f2f2;} sets a light grey background color for the header cells.

This gives us a straight-forward, clean-looking table that is simple to read and navigate. Feel free to modify this code as per your needs to create more personalized styles.

css