CodingBison

We can use HTML elements as selectors and apply CSS designs to them. For example, we can use the "a" tag as a selector -- with that, the CSS rule would apply to all anchor tags on the page.

Let us begin with a description of basic HTML elements that we can select for adding style. The following table lists ways to specify HTML elements as selectors; the description for these elements is self-explanatory. The table lists some of the common HTML elements and is by no means complete! For more on learning HTML elements, please visit our HTML Module.


Table: Using HTML Elements as Selectors
SelectorDescription
headSelects the head element
bodySelects the body element
titleSelects the title element
pSelects all para elements
formSelects all form elements
divSelects all div elements
imgSelects all image elements
aSelects all anchor elements
olSelects all ordered list elements
ulSelects all unnumbered list elements
*Selects all elements on the page

Let us go through a simple example that uses HTML elements as selectors. In terms of structure, the example keeps HTML and CSS content separately. Let us go through the HTML page ("html_selector.html") first and we would see the CSS file ("html_selector.css") next. Among other things, the example contains a paragraph element and an ordered list.

 <!doctype html>
 <html>
 <head>
     <title> Learning CSS: HTML Selectors </title>
     <link type="text/css" rel="stylesheet" href="html_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> Triassic period </li>
     <li> Jurassic period </li>
     <li> Cretaceous period </li>
 </ol>
 </body>
 </html>

Next, we provide the CSS file ("html_selector.css"). The CSS file uses both "p" and "ol" elements as selectors. For the "p" element, it specifies the font to be selected from the sans-serif family and sets the color to blue. For the "o" element, it sets font-weight to bold, color to green, and leaves font type as default.

 p {
     font-family: Helvetica, Verdana, sans-serif;
     color: blue;
 }

 ol {
     font-weight: bold;
     color: green;
 }

Let us load the above page. From the output (provided below), we can see that the style added is different for <p> and <ol> elements. Note that the fonts are different for the two selectors.



Figure: Using HTML Selectors





comments powered by Disqus