Selectors
Selecting by tag name
We have already seen that to style all the paragraphs in a documentInformation in HTML., we use the selectorA way of specifying to which parts of a document the declarations in a rule apply. p
. More generally, we can use a tag nameThe characters used in a tag for a particular element. as a selector when we wish to style all elements with that tag name in the same way. For example, we could style all hyperlink text as green italics using the following rule:
a {
color: green;
font-style: italic;
}
But what if we wish to style some or just one of a particular kind of element instead of all elements of that type?
Selecting by class
Classes are very handy for styling, as they allow us to assign elements to classes based on how we would like them to be styled. For example, if we wish to alternate the colours of odd and even paragraphs, we can assign odd paragraphs to the class odd
, even paragraphs to the class even
, and use the following rules:
.odd {
color: blue;
}
.even {
color: red;
}
Notice that there is a period put in front of the name of the class in each selector.
Caution!
Pay attention to what is done where:
- Assigning elements to classes takes place in the HTML document.
- The rules are placed in the CSS stylesheet.
Selecting by ID
At times we wish to handle a specific element differently from the others. In that type of situation, we can use the ID as a selector. To distinguish among using tag names, classes, and IDs as selectors, a number sign is placed before the ID value:
#special {
font-style: oblique;
}
Syntax summary
Selector | Syntax |
---|---|
element | tag name |
class | period followed by class value |
ID | number sign followed by ID value |