Welcome to our guide on HTML Table Styling! In this lesson, we'll dive into how to style tables using HTML and CSS to make them more appealing and practical for real-world projects.
A table in HTML is used to organize data in a tabular format. It consists of rows and columns, where each cell (intersection of a row and a column) can contain information.
<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>
<!-- More rows... -->
</table>š” Pro Tip: <th> elements are used for table headers, and <td> elements are used for table data.
HTML provides some basic table attributes to help with styling.
<table border="1" width="100%">
<!-- Table content... -->
</table>border attribute controls the table border width (in pixels).width attribute sets the table's width (percentage of its container or a fixed value).However, for more control over the appearance of tables, we'll need to use CSS. Let's create a simple CSS file called styles.css and link it to our HTML document.
<head>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>In our styles.css file, we can target the table and its elements to style them.
table {
border-collapse: collapse;
width: 100%;
}
th, td {
border: 1px solid black;
padding: 8px;
text-align: left;
}š” Pro Tip: border-collapse: collapse removes the spaces between cells' borders.
We can also style individual rows and columns using CSS selectors.
tr:nth-child(even) {
background-color: #f2f2f2;
}
th:first-child {
color: red;
}š” Pro Tip: tr:nth-child(even) selects even rows, and th:first-child selects the first header in each row.
To make our tables responsive, we can use media queries and adjust the table layout for different screen sizes.
@media only screen and (max-width: 600px) {
table, th, td {
width: 100%;
}
}š” Pro Tip: Media queries allow us to target specific screen sizes and adjust our styles accordingly.
What is the purpose of the `border-collapse` property in CSS?
What does `tr:nth-child(even)` select in our CSS?
With the knowledge you've gained, let's create a simple, styled table using HTML and CSS.
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="styles.css">
<title>HTML Table Styling Example</title>
</head>
<body>
<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>
<!-- More rows... -->
</table>
</body>
</html>In our styles.css file:
table {
border-collapse: collapse;
width: 100%;
}
th, td {
border: 1px solid black;
padding: 8px;
text-align: left;
}
tr:nth-child(even) {
background-color: #f2f2f2;
}Congratulations! You've learned the basics of HTML table styling. With this knowledge, you can create stunning and responsive tables for your projects. Keep practicing, and you'll be a master in no time! šš