CSS selectors

February 11, 2024 - Reading time: 4 minutes

Target the right element is a must-know. Here's a recap of the available options. Examples are for the following structure:

<h2>Some title</h2>
<p>A paragraph</p>
<div>
<p>I am child of div</p>
<p>The guy up there is my bro.</p>
<section>
<p>Lonely paragraph</p>
</section>
<p>Third brother.</p>
</div>
<p>Out of div</p>
<p>Same</p>

As always, a demo is available on CodePen.

Combinators

Target a list of elements

Separate the elements with a ,.

h2, section {
font-weight: bolder;
color: navy;
}

Target all descendants of an element

Separate the parent element from the descendant element with a space.

div p {
text-decoration: underline;
}

Target all children of an element

Separate the parent element from the child element with a >.

body > p {
font-family: monospace;
}

Target the next sibling

Separate the first bro element from the second with a +.

div + p {
text-align: center;
}

Target all next siblings

Separate the first bro element from the other ones ~.

div ~ p {
width: 20%;
padding: 0.5em;
border: 0.25em solid indianred;
}

Pseudo-class selectors

A full list can be found on MDN Web Docs.

Target all first child from a parent element

Use a pseudo class after the element's name you want to target:

p:first-child {
letter-spacing: 0.25em;
}

Target every x element of a type from a parent

p:nth-of-type(3n) {
color: blue;
}

Pseudo-elements

Locate a starting point then create inline elements or specific decoration. For instance:

h2::before {
content: "♥ ";
}

h2::selection {
background-color: gold;
}

Attribute selectors

There's no attribute in the demo page. See attribute selectors