The element selector selects all elements with the specified element name.
Example, select and style all <p> elements:
p {
background-color: yellow;
}
element {
css declarations;
}
The .class selector selects elements with a specific class attribute.
To select elements with a specific class, write a period (.) character, followed by the name of the class.
You can also specify that only specific HTML elements should be affected by a class.
To do this, start with the element name, then write the period (.) character, followed by the name of the class (look at Example 1 below).
HTML elements can also refer to more than one class (look at Example 2 below).
.class {
css declarations;
}
The id selector uses the id attribute of an HTML element to select a specific element.
The id of an element should be unique within a page, so the id selector is used to select one unique element!
To select an element with a specific id, write a hash (#) character, followed by the id of the element.
The style rule below will be applied to the HTML element with id="para1":
Example:
#para1 {
text-align: center;
color: red;
}
The descendant selector matches all elements that are descendants of a specified element.
The following example selects all <p> elements inside the <div> element.
Example:
div p {
background-color: yellow;
}
The universal selector, written "*", matches the name of any element type. It matches any single element in the document tree.
If the universal selector is not the only component of a simple selector, the "*" may be omitted. For example:
A pseudo-class is used to define a special state of an element.
For example, it can be used to:
The syntax of pseudo-classes:
selector:pseudo-class {
property:value;
}When several selectors share the same declarations, they may be grouped into a comma-separated list.
In this example, we condense three rules with identical declarations into one. Thus,
h1 { font-family: sans-serif }
h2 { font-family: sans-serif }
h3 { font-family: sans-serif }
is equivalent to:
h1, h2, h3 { font-family: sans-serif }