What are CSS selectors?
CSS selectors are used to define the elements you want to style with CSS. There are many different types of CSS selectors, each with their own unique syntax. These tell the browser which elements to apply CSS property values to.
Types of CSS Selectors
Universal Selector
The asterisk (*) is the universal selector in CSS. By default, it selects all elements in a document.
*{
border: 0;
font-family: 'Poppins',serif;
}
Type Selector
A type selector selects all HTML elements that have a given node name. For example, “a” would select all elements and apply the CSS property values to them. “Input” would select all elements, “span” all elements and so on.
span {
background-color: orange;
}
Class Selector
A class selector selects all elements that have a given class name. For example, .intro would select any element that has a class of “intro” just as .index would select any element that has a class of “index.”
.container {
color: orange;
}
ID Selector
An ID selector selects an element based on its ID attribute. For example, #toc will select the element that has the ID "toc.” Please note that this selector only works if the value given in the selector matches the element’s ID attribute exactly.
#top {
color: orange;
text-align: right;
}
CSS [attribute] Selector
The [attribute] selector is used to select elements with a specified attribute.
The following example selects all elements with a target attribute:
a[target] {
background-color: yellow;
}
Pseudo-class Selector
A pseudo-class selector applies CSS to a selected element or elements only when in a special state. For example, :hover will only style an element when a user hovers over it. Other common examples are :active, :visited, and :invalid
a:link {
color: #0000FF;
}
a:visited {
color: #00FF00;
}
a:hover {
color: #FF00FF;
}