CSS Selectors Part 2

Aurum Linh
2 min readOct 31, 2016

--

In my last post, I went over selecting by type, id, class, and descendants. In this next reference, I’ll provide examples for sibling and child selectors.

Adjacent Sibling Selector

A + B

Selects all B elements that directly follow A as a sibling. An element is a sibling to another when they are both on the same level or depth. In HTML, siblings will be at the same indentation level.

To select every <span> that directly follows a <div>:

div + span {}

To select every element with a class “selected” that directly follows a <p>:

p + .selected {}

General Sibling Selector

A ~ B

Selects elements that follow another element.

To select all elements with class “selected” after a <p>:

p ~ .selected {}

To select all elements with an id “post” after a <div>:

div + #post {}

Child Selector

A > B

Selects elements that are direct children of other elements. A child element is any element that is nested directly in another element. Elements that are nested deeper than that are descendant elements.

To select all elements with class “post” in an element with id “newsfeed”:

#newsfeed < .post {}

To select all <p> within an <article>:

article < p {}

First-Child Pseudo Selector

:first-child

Selects the first child of an element.

To select all first-child elements:

:first-child {}

To select all <a> first-child elements:

a:first-child {}

To select all <a> first-child elements in <p>:

p a:first-child {} 

Only-Child Pseudo Selector

:only-child

Selects any element that is the only element inside another one

To select all elements that are only-children:

:only-child {}

To select <p> that is the only element inside of any other element:

p:only-child {}

To select <span> that is the only element inside of a <div>:

div span:only-child {}

Last-Child Pseudo Selector

:last-child

Selects last element inside another element.

To select all last-child elements:

:last-child {}

To select all last-child <a> elements:

a:last-child {}

To select the last <p> in a <div>:

div p:last-child {}

Nth Child Pseudo Selector

:nth-child(A)

Selects the nth child element in the another element

To select every element that is the 4th child of another element:

:nth-child(6){}

To select the third <p> in every <div>:

div p:nth-child(3) {}

And that’s all for now! In addition to the type, id, class, and descendant selectors, the child and sibling selectors give you means for using the flexibility of CSS to your advantage.

In the next post, I’ll cover styling user interaction with links on your page.

--

--

Aurum Linh

Creatrix of Atlas Lab • How machines make decisions is a human rights issue