CSS Table Borders
Tables have been an integral part of web design since the early days of the internet. They provide a structured way to organize and present data. While the HTML structure defines the content and layout of a table, Cascading Style Sheets (CSS) allow you to enhance its appearance. In this article, we’ll explore how to add stylish borders to your HTML tables using CSS.
Basic Table Structure
Before diving into styling, let’s set up a basic HTML table structure. Create an HTML file and add the following code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Table Borders</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<table>
<tr>
<th>Header 1</th>
<th>Header 2</th>
<th>Header 3</th>
</tr>
<tr>
<td>Row 1, Cell 1</td>
<td>Row 1, Cell 2</td>
<td>Row 1, Cell 3</td>
</tr>
<tr>
<td>Row 2, Cell 1</td>
<td>Row 2, Cell 2</td>
<td>Row 2, Cell 3</td>
</tr>
</table>
</body>
</html>
In this example, we have a simple table with headers and data cells.
Styling with CSS Borders
Now, let’s add some CSS to style the borders of our table. Create a file named styles.css
and link it to your HTML file.
/* styles.css */
table {
border-collapse: collapse;
width: 100%;
}
th, td {
border: 1px solid #ddd;
padding: 8px;
text-align: left;
}
th {
background-color: #f2f2f2;
}
/* Optional: Add hover effect on table rows */
tr:hover {
background-color: #f5f5f5;
}
Let’s break down the CSS:
border-collapse: collapse;
: This property ensures that table borders are collapsed into a single border. It gives a cleaner and more consistent look.border: 1px solid #ddd;
: This rule adds a 1-pixel solid border with a light gray color to both header cells (th
) and data cells (td
).padding: 8px;
: Provides some space between the cell content and the cell border.text-align: left;
: Aligns the text inside cells to the left.background-color: #f2f2f2;
: Sets a background color for header cells to distinguish them from data cells.tr:hover
: Applies a background color change when hovering over a table row, enhancing the visual experience.
Feel free to modify these styles according to your design preferences.
With these CSS rules in place, you’ve added a polished and professional look to your HTML table. Experiment with different border styles, colors, and hover effects to match the overall aesthetic of your website.