In This article we explains the methods for changing the background colors of a table.
Below are some examples of applying background color to a table in HTML.
Background Color for the Whole Table
<!DOCTYPE html> <html lang="en"> <head> <title>Background Color for the Whole Table </title> </head> <body> <table style="width:100%;text-align:left;background-color:yellow;"> <tr> <th>Table Header</th> <th>Table Header</th> </tr> <tr> <td>Table cell</td> <td>Table cell</td> </tr> <tr> <td>Table cell</td> <td>Table cell</td> </tr> </table> </body> </html>
Output:
Background Color of a Table Row
If you want to change another color then You can also change the background color of an individual table cell. Here, we add a different background color to the first row, which happens to be the table header row.
<!DOCTYPE html> <html lang="en"> <head> <title>Background Color of a Table Row </title> </head> <body> <table style="width:100%;text-align:left;background-color:yellow;"> <tr style="background-color:#000; color:#fff;"> <th>Table Header</th> <th>Table Header</th> </tr> <tr> <td>Table cell</td> <td>Table cell</td> </tr> <tr> <td>Table cell</td> <td>Table cell</td> </tr> </table> </body> </html>
Output:
HTML table background color with the border attribute Using Classes
Here’s an example of setting the table’s background color and other properties using a CSS class.
<!DOCTYPE html> <html lang="en"> <head> <title>Example of Table Background Color with border </title> <!-- CSS --> <style> .myTable { width: 100%; text-align: left; background-color: #fff; border-collapse: collapse; font-family: 'Nunito', sans-serif; } .myTable th { background-color: #333; color: white; font-weight:bold; font-size:18px; } .myTable td, .myTable th { padding: 10px; border: 1px solid #ddd; } </style> </head> <body> <!-- HTML --> <table class="myTable"> <tr> <th>Header</th> <th>Header</th> </tr> <tr> <td>Table cell</td> <td>Table cell</td> </tr> <tr> <td>Table cell</td> <td>Table cell</td> </tr> </table> </body> </html>