Tables in CSS Language
Tables are a fundamental way to organize and present data on the web. Whether you’re creating a pricing chart, displaying statistics, or simply laying out content in a structure
d grid, tables are an essential tool in a web developer’s arsenal. In this post, we’ll explore how to style tables using CSS to make them not only functional but also visually appealing.The Basic Structure of a Table
Before we dive into CSS styling, let’s review the basic HTML structure of a table. Tables are built using a combination of HTML tags, such as <table>
, <tr>
, <th>
, and <td>
. Here’s a simple example:
<table>
<tr>
<th>Header 1</th>
<th>Header 2</th>
</tr>
<tr>
<td>Row 1, Cell 1</td>
<td>Row 1, Cell 2</td>
</tr>
<tr>
<td>Row 2, Cell 1</td>
<td>Row 2, Cell 2</td>
</tr>
</table>
This will create a basic table with two headers and two rows, each containing two cells.
Styling Tables with CSS
Now, let’s enhance the look and feel of this table using CSS. You can use CSS to change fonts, colors, borders, and more to match the overall design of your website.
1. Basic Styling
table {
width: 100%;
border-collapse: collapse;
}
th, td {
border: 1px solid #ddd;
padding: 8px;
text-align: left;
}
th {
background-color: #f2f2f2;
}
tr:hover {
background-color: #f5f5f5;
}
In the code above, we set the table’s width to 100%, collapse the borders between cells, and add some spacing and alignment. We also add a light gray background to the header row and a hover effect on rows to make the table more user-friendly.
2. Alternating Row Colors
To improve readability, you can apply alternating row colors:
tr:nth-child(even) {
background-color: #f2f2f2;
}
This code will make even rows have a light gray background, creating a zebra-striped effect.
3. Centered Text in Headers
You can center the text in header cells:
th {
background-color: #f2f2f2;
text-align: center;
}
4. Adding Borders
To create a border around the entire table, you can add:
table {
border: 1px solid #333;
}
5. Cell Specific Styling
You can also apply unique styles to specific cells by using class or ID attributes:
<td class="highlight">Highlighted Cell</td>
td.highlight {
background-color: yellow;
font-weight: bold;
}
Discover more from PiEmbSysTech
Subscribe to get the latest posts sent to your email.