Basic CSS Selectors
There are four types of basic selector, namely, the Universal Selector, Type or Element Selectors, ID Selectors and Class Selectors.
Universal Selector
The Universal Selector allows you to target every element on a page, or, if used in conjunction with a Descendant Selector, described below, targets all elements based on their relationship with other elements. In its most basic form, the example below sets the text colour to black and the font size to 18px for all elements on a page.
* {
color: black;
font-size: 18px;
}
Type Selectors
Type Selectors, also known as Element Selectors, use HTML tags as the selector, so that all instances of that HTML tag use the same styling. The example below gives all paragraphs a text colour of black.
p {
color: black;
}
ID Selectors
ID Selectors allow you to give a unique identifier to a specific HTML element, so that only the one particular instance of an HTML tag is targeted for styling. An ID only needs to be unique for a particular page, so it can be used on more than one page. Below is the HTML for a paragraph that has been given the ID of 'blue', along with the corresponding CSS to style it.
HTML:
<p id="blue">This is a paragraph with blue text.</p>
CSS:
#blue {
color: blue;
}
All ID Selectors are preceded with a hash symbol in the style sheet, making them easy to identify. Note that if the above Type Selector was present in the same style sheet then all paragraphs would have black text, except for this one with the ID of 'blue'. Potentially an ID Selector could be used on different elements on each page, so for example, it could be used on a paragraph on one page and a heading on another. If it was so desired, its use could be limited to just paragraphs by re-writing it as follows.
p#blue {
color: blue;
}
Class Selectors
Class Selectors, like ID Selectors, allow you to give an identifier to HTML elements. The difference between the two however is that a Class Selector can be applied to multiple elements on a page, so, as in the below example, more than one paragraph can be given a class that makes the text colour blue.
HTML:
<p class="blue">This is a paragraph with blue text.</p> <p class="blue">This is another paragraph with blue text.</p>
CSS:
.blue {
color: blue;
}
All Class Selectors are preceded with a '.' in the style sheet, again, as with ID Selectors, making them easily identifiable. The above example, as it is currently written, can be used on multiple types of element such as paragraphs and headings, but it can be re-written to limit its use to just paragraphs, for example, as follows.
p.blue {
color: blue;
}