Selectors in CSS once and for all!

Made by draw.io

A question/problem that many may have faced while “learning/working” is that they are dubious or mistaken about choosing a selector. Since they don’t know which selector to use, they get stuck in an irritating loop and after trying to work it out for some time, they end up backing down from this idea and instead turn to DOM Manipulation using JavaScript or even worse, changing the DOM Structure!

CSS has quite a variety of selectors but not all of them are used regularly in practice. Some have a specific usage that can be determined by their names and others remain a mystery but you don’t need to know ’em all. The purpose of this article is to point out and explain the most useful selectors once and for all!

You can see a general diagram of the most used and important selectors below but before we talk about them you should know that I have not mentioned the class and ID selector ( ‘ . ‘ , ‘ # ‘ ). So if you don’t already know about these two, instead of reading this article I recommend you to start with the basics of CSS.

1 ) Descendant selector

To use this one you don’t need to use a specific character. It is the space between elements and it selects all the descendants of the element in question.

Imagine we have :

Question: Which paragraph is the style applied to?

Answer: To all

When you are using the descendant selector, indentation of the elements is not important and they only need to be a descendant of the main wrapper.

So even in the situation below, the styles will be applied to the paragraphs as long as they are descendants of “post”.

2) Direct child selector (>)

Only the elements that are directly mentioned as a child to the parent element are selected, not the ones that are inside a second or third wrapper element.

Look at the last example rewritten with the direct child selector:

Question: Which paragraph is the style applied to?

Answer: The first paragraph after the section tag and the last one before closing the section tag

3) Sibling selector

3.1) General Sibling Selector (~)

After using this selector, all the elements on the right side of “~” (Which are of the same kind) are selected, ONLY IF they have the same parent.

Question: Which paragraph is the style applied to?

Answer: paragraph 19

The selected paragraphs must:

Come after the element “H1”

Have the same parent as “H1”

Since the two conditions above are not true for paragraphs 1, 5, 9, 15, and 23 the style will not be applied to them.

Why?Lines 1, 5, 9: They are placed before “H1”.

Lines 15, 23: Although they come after “H1”, they don’t have the same parent as “H1”.

3.2) Adjacent sibling selector (+)

Using this selector, we only select the first element on the right side of “+”. So if we used this selector in the last example, none of the paragraphs would be selected. But if we had a number of paragraphs right after “H1”, no matter how many, only the first one would be selected.

Question: Which paragraph is the style applied to?

Answer: Just the one after “H1” (paragraph 14)

4) Attribute Present Selector

HTML tags have lots of attributes which we can use in CSS.

For example:

In the examples above we’ve used the “href”, “type”, and “id” attributes but we can use others like “form” or “input” or etc.

The characters $, ^, * may seem a bit confusing but wait a second:

^= : The attribute selected for the used element starts with what is inside (‘ ‘)

*= : The attribute selected for the used element includes what’s inside (‘ ‘)

$= : The attribute selected for the used element ends with what is inside (‘ ‘)

Let’s take another look at the example:

In the first item we just used the equal sign and it contains “https://medium.com”. This selector picks the “a” tags that exactly contain medium’s href.

In the second item the “a” tags that their href begins with ‘https://nest’ are selected.

In the third item the “a” tags that their href ends in. ‘.org’ are selected.

In the fourth item the “a” tags that their href contains ‘docker’ are selected.

In the fifth item ‘I’ type ol lists are selected.

In the sixth item the span inside div with the ID “unique_div” is selected.

5) pseudo-classes

pseudo-classes are used at times when we need to have access to an element in a certain state or situation. Below we are going to discuss 8 of the most used ones.

5.1) link pseudo classes

a:link {…} ~> Links that have not been visited and are in their normal state.
a:visited {…} ~> Links that have been visited.

5.2) User action pseudo classes

a:active‌ {…} ~> the link that is active now
Element:hover {…} ~> the element which the cursor is on now
Element:focus {…} ~> the element that is touched right now

5.3) User interface pseudo classes

input:enabled {…} ~> active inputs
input:disabled {…} ~> inactive inputs
input:checked {…} ~> checked checkboxes
input:indeterminate {…} ~> when there are no changes applied to a radio box or a select box

5.4) Structural & Position Pseudo-classes

Element:first-child {…} ~> selects the first child
Element:last-child {…} ~> selects the last child
Element:first-of-type {…} ~> the first child of a parent from a specific element
Element:last-of-type {…} ~> the last child of a parent from a specific element
Element:only-child {…} ~> the child is selected only if it’s the only child to the parent element

If you find it a bit difficult to understand “only-child” look at the example below:

div span:only-child {
color: firebrick;
}
<section>
<div>
<span>Text</span>
<span>Text</span>
<div>
<span>
This will be selected</span>
</div>
</div>
</section>

The only selected span is the one that is div’s only child.

5.5) Numbers & Expressions Pseudo-classes

1. Element:nth-child(n) : The nth child is directly selected.

2. Element:nth-child(an) : The child’s of the multiples of ‘a’ are selected.

3. Element:nth-child(n+b) : This one’s a bit different. Considering b’s value, the children are selected starting from b itself and on.

Example :

li:nth-child(n + 4) ~> Selected from the fourth 'li' onwards (the fourth item itself is also selected)

4. Element:nth-child(an+b) : Here, n starts from 0 and after getting multiplied by a, it’s added to b and then the children are selected.

Example :

li:nth-child(4n+7){...} ~>(4×0)+7, (4×1)+7, (4×2)+7 = children 11 and 15 are selected.

5. Element:nth-child(an-b) : Here too, n starts from 0 and after getting multiplied by a, b is subtracted.

li:nth-child(6n-4){...} ~> (6×0)-4, (6×1)-4, (6×2)-4 = children 2, 8, and 14 are selected

5.6)Empty Pseudo-class

Here, elements are selected that are either empty or containing just a comment. But notice that since space and tab are strings they are not considered as empty.

For example:

#post span:empty {…}
<section id=”post”>
<span></span> ~> This will be selected
<span> </span> ~> This will not be selected (because of space)
<span><!--comment--></span> ~> This will be selected
</section>

5.7)Negation Pseudo-class

As you can probably guess by the name, this selector does not include the elements mentioned inside ( :not() )

An interesting thing about this selector is that it can be combined with the previous ones, for example:

li:not(.li-elements) {…} ~> a list of items not including the mentioned class
ul li:not(:nth-child(2n)) {…} ~> a list of items are selected that are not multiples of 2.

5.8) Textual Pseudo-elements

Element::after {…} ~> using this selector, a pseudo element is added to the end of the selected element, which can have content or/and style. It’s usually used to add an animation or icon for complementary purposes.
Element::before {…} ~> This one is like after, with the only difference being the pseudo elements positioning moved to the beginning of the selected element.
Element::first-letter {…} ~> The first textual character inside our specific element is selected. You must have seen this one in publications websites.
Element::first-line {…} ~> selects the first line of the specific element.
Element::placeholder {…} ~> If the specific element has a placeholder, it’s selected and you can add a style to it.
Element::selection {…} ~> when you select a text in a web page, the selected piece of text has a certain color and background color. Depending on the OS’s user agent there’s a default accent color, for example, it’s blue and white for Windows, orange and white for Ubuntu, and macOS white. 
Bottomline being, this color is changeable and this is made possible using this selector.

For example :

::selection {
background:#0f94e9;
color:#fff
}

--

--

--

frontend developer with extensive experience in javascript , modern web paradigms and widely used frameworks .

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

The Complete Go:Golang Bootcamp

Power BI — RLS, part 1

5 Unique ways to trigger your UiPath Bots (Without Orchestrator API)

Are Microservices the Future of Business Applications? — Bot Techie

What people don’t get about value stream management

How to Create an Action on Google for Google Assistant.

Everything You Need to Know About Networking Issues

[LeetCode]#507. Perfect Number

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Amirsina Shadkami

Amirsina Shadkami

frontend developer with extensive experience in javascript , modern web paradigms and widely used frameworks .

More from Medium

Create a Landing Page Design using CSS framework: Sass Part 2.

Color Extraction Tools for Front End Web Development

Flexbox vs Grid: when and where to use.

Let’s talk Sass and why you should use it for your Stylesheets