Padding and spacing are essential concepts in HTML tables for controlling the appearance and layout.
Padding
Padding is the space between the content of a cell and its border. It creates some breathing room inside the cell, making the content more readable and visually appealing.
Spacing
Spacing between cells is managed using the border-spacing property, which defines the space between the borders of adjacent table cells.
Table with Padding Example
a table with padding applied to its cells
<!DOCTYPE html> <html> <head> <style> table { width: 50%; border-collapse: collapse; } th, td { border: 1px solid black; padding: 15px; /* Add padding to cells */ } </style> </head> <body> <table> <tr> <th>Header 1</th> <th>Header 2</th> </tr> <tr> <td>Cell 1</td> <td>Cell 2</td> </tr> <tr> <td>Cell 3</td> <td>Cell 4</td> </tr> </table> </body> </html>
each cell has 15 pixels of padding, creating space between the cell content and its border.
Table with Border Spacing
a table with border spacing
<!DOCTYPE html> <html> <head> <style> table { width: 50%; border-collapse: separate; border-spacing: 10px; /* Add spacing between cells */ } th, td { border: 1px solid black; padding: 10px; } </style> </head> <body> <table> <tr> <th>Header 1</th> <th>Header 2</th> </tr> <tr> <td>Cell 1</td> <td>Cell 2</td> </tr> <tr> <td>Cell 3</td> <td>Cell 4</td> </tr> </table> </body> </html>
there is a 10-pixel space between the borders of the table cells.
Combining Padding and Border Spacing
You can also combine both padding and border spacing
<!DOCTYPE html> <html> <head> <style> table { width: 50%; border-collapse: separate; border-spacing: 10px; } th, td { border: 1px solid black; padding: 15px; } </style> </head> <body> <table> <tr> <th>Header 1</th> <th>Header 2</th> </tr> <tr> <td>Cell 1</td> <td>Cell 2</td> </tr> <tr> <td>Cell 3</td> <td>Cell 4</td> </tr> </table> </body> </html>
each cell has 15 pixels of padding, and there is a 10-pixel space between the borders of the table cells.
By adjusting the padding and spacing properties, you can control the look and feel of your tables to make them more visually appealing and readable.