In this example we are going to see how we can specify the color of a cell in HTML. For this we are going to support you in the CSS styling language.
The first thing we have to know to specify the color of a cell in HTML is how a table is built. A table is built from three basic elements: table, tr and td. The table element represents the table, the element tr represents a row or set of cells, which will be represented by the td element.
For example a table in HTML would be as follows:
| Spain | Madrid | 504,645 km2 | 46.6 M |
So to be able to specify the color of a cell in HTML we must work with the td element and its associated styles. In this case we are going to work with the background-color property which allows us to specify the background color of an element.
This way when specifying the style background-color we could write the following:
table td {
background-color: #f00;
}
Although what we are going to achieve is that all the cells have a blue background color.
In case we want to specify the color of a cell in HTML, but for this cell to be specific, it is recommended that we use the classes. That is, we are going to define some classes in CSS which we are going to associate with the cells.
For example we can create three importance classes:
table .height {
background-color:red;
}
table .medium {
background-color:yellow;
}
table .under {
background-color:green;
}
When writing the selectors we see that we have anticipated the table element so that these classes can only be set within a table.
The names of the classes in CSS will always start with a dot (.)
Now what we do is use the class attribute of td element that represents the cells to assign one value or another.
Cell
So our table could look like this:
| Country | Capital | Surface | Inhabitants |
|---|---|---|---|
| Spain | Madrid | 504,645 km2 | 46.6 M |
| Italy | Rome | 301,338 km2 | 60.7 M |
| France | Paris | 675,417 km2 | 66 M |
We see how we have used different classes in different td elements to be able to define the color of a cell in HTML.
