Table borders in HTML define the lines that surround the table, rows, and cells, making the table's structure more visible and organized. Borders can be styled in various ways using HTML attributes or CSS (Cascading Style Sheets).
Here's an example using the HTML border
attribute and CSS for more advanced styling:
Example with the HTML border
Attribute
<table border="1"> <tr> <th>Name</th> <th>Age</th> <th>City</th> </tr> <tr> <td>John Doe</td> <td>30</td> <td>New York</td> </tr> <tr> <td>Jane Smith</td> <td>25</td> <td>Los Angeles</td> </tr> <tr> <td>Mike Johnson</td> <td>40</td> <td>Chicago</td> </tr> </table>
In this example, the border="1"
attribute adds a simple border around the table cells. The border width is 1 pixel.
Example with CSS for More Advanced Styling in Tables
<!DOCTYPE html> <html> <head> <title>HTML Table with CSS Borders</title> <style> table { border-collapse: collapse; width: 50%; } th, td { border: 2px solid black; padding: 8px; text-align: left; } th { background-color: #f2f2f2; } </style> </head> <body> <h2>HTML Table with CSS Borders</h2> <table> <tr> <th>Name</th> <th>Age</th> <th>City</th> </tr> <tr> <td>John Doe</td> <td>30</td> <td>New York</td> </tr> <tr> <td>Jane Smith</td> <td>25</td> <td>Los Angeles</td> </tr> <tr> <td>Mike Johnson</td> <td>40</td> <td>Chicago</td> </tr> </table> </body> </html>
In this example:
- The
border-collapse: collapse;
CSS property collapses the borders into a single border instead of separating them. - The
border: 2px solid black;
CSS property adds a 2-pixel solid black border to each table cell. - The
padding: 8px;
property adds 8 pixels of padding inside each cell. - The
background-color: #f2f2f2;
property adds a light gray background to the header cells (<th>
).
Using CSS for table borders provides more flexibility and control over the appearance of the table.