Selectors
CSS selectors are patterns used to select the elements.
Basics
Element Selector
Selects all instances of a specific HTML element. To style all paragraphs:
p {
color: white;
background: blue;
}
ID Selector
Selects a single element with a specific ID. Use a hash (#) before the ID name. An ID is unique, while a class is not. To avoid conflicts, IDs are rarely used.
#app {}
Class Selector
Selects elements with a specific class. Use a period . before the class name.
Class selectors are the most used ones.
.my-class {}
Attribute Selector
Selects elements based on their attributes. To select all text input:
input[type="text"] {}
Pseudo-class Selector
Pseudo-class selector starts with :.
state
:hover, :focused, :disabled, :focus-within
To select all anchors with mouse cursor on it:
a:hover {}
lang
:lang
<p lang="de"></p>
p:lang(de) {}
first and last
First child:
article *:first-child {}
First child and it is is a paragraph:
article p:first-child {}
First paragraph:
article p:first-of-type {}
Similary, this are last-child and last-of-type.
nth
p:nth-child(n) {}
p:nth-of-type(2n + 1) {}
p:nth-last-type(1) {}
n: 0 1 2 3 ...
2n + 1: 1 3 5 ...
not
p:not(:first-child) {}
Pseudo Elements
Pseudo element selectors starts with double colons :::
p::first-letter {}
p::first-line {}
p::before {}
p::after {}
input::placeholder {}
dialog::backdrop {}
::selection {}
Combining Selectors
Selectors can also be combined in several ways:
Grouping Selectors
You can group multiple selectors that share the same styles by separating them with a comma.
h1, h2, h3 {
color: green;
}
Escendant Selector
This selector targets elements that are nested within a specified parent element.
div p {
color: blue; /* Applies to all <p> elements inside any <div> */
}
Child Selector
The child selector > selects elements that are direct children of a specified parent.
ul > li {
list-style-type: square; /* Applies only to <li> that are direct children of <ul> */
}
Adjacent Sibling Selector
The adjacent sibling selector + selects an element that is immediately following another specified element.
h1 + p {
margin-top: 0; /* Applies to the first <p> that comes directly after an <h1> */
}
Combining Class and Element Selectors
You can combine class selectors with element selectors to target specific elements with certain classes.
button.primary {
background-color: blue;
}