Selectors In CSS
A CSS selector selects the HTML element(s) you want to style.
CSS Selectors
CSS selectors are used to "find" (or select) the HTML elements you want to style. We can divide CSS selectors into five categories:
- Simple selectors
(select elements based on name, id, class) - Combinator selectors
(select elements based on a specific relationship between them) - Pseudo-class selectors
(select elements based on a certain state) - Pseudo-elements selectors
(select and style a part of an element) - Attribute selectors
(select elements based on an attribute or attribute value)
(select elements based on name, id, class)
The element selector selects HTML elements based on the element name.
p {
text-align: center;
color: red;
}
(select elements based on a specific relationship between them)
A CSS selector can contain more than one simple selector. Between the simple selectors, we can include a combinator.
There are four different combinators in CSS:
- descendant selector (space)
- child selector (>)
- adjacent sibling selector (+)
- general sibling selector (~)
(select elements based on a certain state)
A pseudo-class is used to define a special state of an element.
For example, it can be used to:
- Style an element when a user mouses over it
- Style visited and unvisited links differently
- Style an element when it gets focus
a:link {
color: #FF0000;
}
/* visited link */
a:visited {
color: #00FF00;
}
/* mouse over link */
a:hover {
color: #FF00FF;
}
/* selected link */
a:active {
color: #0000FF;
}
(select and style a part of an element)
A CSS pseudo-element is used to style specified parts of an element.
For example, it can be used to:
- Style the first letter, or line, of an element
- Insert content before, or after, the content of an element
color: #ff0000;
font-variant: small-caps;
}