CSS selectors are employed to “locate” or designate the HTML elements targeted for styling.
CSS selectors can be classified into five groups:
The element selector chooses HTML elements according to their element name.
Example
In this context, every <p> element throughout the page will exhibit center alignment and possess a red text color.
#para1 { |
The id selector targets a specific HTML element using its id attribute.
Since an element’s id is unique within a page, the id selector is ideal for selecting a single, unique element.
To select an element with a specific id, precede the id with a hash (#) character.
Example
The following CSS rule will be applied to the HTML element with the id=”para1″:
#para1 { text-align: center; color: red; } |
Note: An id name cannot begin with a number! |
The class selector targets HTML elements that possess a particular class attribute.
To select elements with a specific class, prepend the class name with a period (.) character.
Example
In this example, all HTML elements with the class=”center” will be styled to appear in red and aligned to the center.
.center { |
You can also indicate that only particular HTML elements should be influenced by a class.
Example
In this instance, solely <p> elements having the class= “center” will display as red and centered-aligned.
p.center { |
HTML elements can also be associated with multiple classes.
Example
In this instance, the <p> element will be styled based on both class=”center” and class=”large”.
<p class=”center large”>This paragraph refers to two classes.</p>
Please be aware: Class names cannot commence with a number! |
The universal selector (*) targets all HTML elements present on the page.
Example
The following CSS rule will impact every HTML element on the page:
* { text-align: center; color: blue; } |
The grouping selector selects all HTML elements sharing the same style definitions.
Consider the following CSS code (where the h1, h2, and p elements have identical style definitions):
h1 { |
It would be more efficient to consolidate the selectors to minimize the code.
To group selectors, simply separate each selector with a comma.
Example
In this instance, we’ve organized the selectors from the preceding code into groups.
h1, h2, p { |
Selector |
Example |
Example description |
#id |
#firstname |
Select the element that has the id “firstname” |
.class |
.intro |
Selects all elements that have the class “intro” |
Element.class |
p.intro |
Select only ‘<p>’ element that have the class “intro” |
* |
* |
Selects every element |
Element |
p |
Select every ‘<p>’ element |
Element,element,.. |
Div,p |
Selects all <div>elements and all <p>elements |