In addition to selecting HTML elements by their tag and CSS class, CSS allows us to select them using CSS id. CSS allows only one element on a page that can have a given CSS id. When specifying selectors for these types, CSS uses the convention of a hash character ("#").
Let us now look at an example that highlights selection of elements using CSS id. The HTML content in this example (provided below) is fairly simple. It has a paragraph element and an ordered list child list elements. Among these HTML elements, we use three CSS IDs: "green", "blue" and "red". Next, the ordered list that has its own list element and the example assigns different ids to different list elements.
<!doctype html> <html> <head> <title> Learning CSS: CSS ID Selectors </title> <link type="text/css" rel="stylesheet" href="id_selector.css"> </head> <body> <p> The Mesozoic Era was the age of dinosaurs. This Era lasted 180 million years and consisted of the following three periods. The evolution of dinosaurs started during the Triassic period, they became dominant animals during the Jurassic period, and became extinct at the end of the Cretaceous period. </p> <ol> <li id="red"> Triassic period </li> <li id="green"> Jurassic period </li> <li id="blue"> Cretaceous period </li> </ol> </body> </html>
Our example shows the usage of CSS ids so that we can be more specific. For that, it locates the three different CSS ID elements and assigns different rules to them.
/* This rule adds style to the "red" ID element. */ #red { font-family: Helvetica, Verdana, sans-serif; font-weight: bold; color: red; } /* This rule adds style to the "green" ID element. */ #green { font-family: Helvetica, Verdana, sans-serif; font-weight: bold; color: green; } /* This rule adds style to the "blue" ID element. */ #blue { font-family: Helvetica, Verdana, sans-serif; font-weight: bold; color: blue; }
If we now load our HTML page, we would see that only the three <li> elements have have different styles. The <p> element continues to have the default style. Here is the output: