7 min read

Mastering CSS Selectors

Aside from mastering the display and position CSS rule, learning how to use the CSS selectors is the most important skill you need to develop. You don't have to remember the syntax of each of them, but keep them on your radar to be able to develop the right strategies when building your CSS stylesheet.

Why Do We Need to Learn about Selectors?


Completing a stylesheet is like having a little war between selectors, – you are constantly overriding previously defined styles with new ones:

//You first might want all the H2 tags to be font-size: 14px; and color: blue;
h2{
    font-size: 14px;
    color: blue;
}

//But then you have a very particular page where the background is also blue, so you need your headings to be white

h2{
    color: white;
}

This happens all the time and, at some point it, can be challenging to override previous styles. You must organize your styles properly and start from the least specific to the most specific.

This "very specific" selectors will help you a lot. They will be your best weapon when fighting your styles war!

The Child Selector


#someDiv > p {
    color: blue;
}

This statement takes the paragraph tags that are children of the div and turns them blue. Note that it only works for the children of that div – not necessarily for all of the descendants. Let’s explore this further with the following example.

The Adjacent Sibling Selector


p + p {
    color: red;
}

We used the adjacent sibling selector to change the second and third paragraph to red. This seems very tricky, doesn’t it? Instinctively, we would expect the first paragraph to be red as well. After all, the first paragraph is on the same level as the next two, and, has siblings.

However, this selector only applies to elements that are preceded by something else. In this instance, only the paragraphs preceded directly by a sibling paragraph will be targeted.

The first paragraph in the list is preceded by the div, so it remains unchanged.

The Almighty Asterisk


#someDiv * {
    color: red;
}

The previous CSS code turns red every element inside a specific div – this includes items such as links, that have a default color set to something else and wouldn’t be affected by simply targeting the div.

div * p {
    color: red;
}

You can take this as far as you want – the following targets the "great grandchildren" of the div. You will find this chaining method used frequently in CSS debugging tricks.

Attribute Value Selector


a[href='http://4geeksacademy.com/'] {color: blue;}

If we want to change the font color of the "Design Shack" link, we could use :pseudo selectors. However, doing so would assume that the list stays in that order, and, browser support isn’t the best. Instead, what we can do is use an attribute selector to target the specific "href" that we’re interested in.

Arbitrary Substring Attribute Value Selector


div[id*='section'] {color: red;}

The following code targets any div with the word "section" in the title. It can be "section3" or "section-Four" – it doesn’t matter. As long as it contains the indicated string, the subsequent styles will apply.

Pseudo Class Selectors


a:link{color: green;}
a:visited{color: yellow;}
a:hover{color: blue;}
a:active{color: red;}

You can assign a different color to any link on the website, depending on its status:

  • :link default color, before clicking on it.

  • :visited after clicking the link.

  • :hover when the cursor is over the link.

  • :active when the cursor is clicking on the link.

input{padding: 5px;}
input:disabled{
    background: #ddd;
    color: #949494;
    border: 2px solid black;
}
input:focus{font-size: 2em;}
input:enabled{ border: 2px solid black;}

It is very important to take enough time to style our forms. Styling is the best way to tell the user that an input is either disabled, checked, or that the cursor is over a particular input.

Position-based pseudo selectors

#myUL li:first-child{background: blue;}
#myUL li:nth-child(3){background: orange;}
#myUL li a:first-of-type{background: green;}

You can apply styles to elements based on their position.

Here is a list of the most used Pseudo-Classes:

SelectorExampleExample description
:activea:activeSelects the active link
:checkedinput:checkedSelects every checked <input> element
:disabledinput:disabledSelects every disabled <input> element
:emptyp:emptySelects every <p> element that has no children
:enabledinput:enabledSelects every enabled <input> element
:first-childp:first-childSelects every <p>element that is the first child of its parent
:first-of-typep:first-of-typeSelects every <p> element that is the first <p> element of its parent
:focusinput:focusSelects the <input> element that has focus
:hovera:hoverSelects links on mouse over
:in-rangeinput:in-rangeSelects <input> elements with a value within a specified range
:invalidinput:invalidSelects all <input> elements with an invalid value
:lang(language)p:lang(it)Selects every <p> element with a lang attribute value starting with "it"
:last-childp:last-childSelects every <p> element that is the last child of its parent
:last-of-typep:last-of-typeSelects every <p> element that is the last <p> element of its parent
:linka:linkSelects all unvisited links
:not(selector):not(p)Selects every element that is not a <p> element
:nth-child(n)p:nth-child(2)Selects every <p> element that is the second child of its parent
:nth-last-child(n)p:nth-last-child(2)Selects every <p> element that is the second child of its parent, counting from the last child
:nth-last-of-type(n)p:nth-last-of-type(2)Selects every <p> element that is the second <p> element of its parent, counting from the last child
:nth-of-type(n)p:nth-of-type(2)Selects every <p> element that is the second <p> element of its parent
:only-of-typep:only-of-typeSelects every <p> element that is the only <p> element of its parent
:only-childp:only-childSelects every <p> element that is the only child of its parent
:optionalinput:optionalSelects <input> elements with no "required" attribute
:out-of-rangeinput:out-of-rangeSelects <input> elements with a value outside a specified range
:read-writeinput:read-writeSelects <input> elements with no "readonly" attribute
:requiredinput:requiredSelects <input> elements with a "required" attribute specified
:rootrootSelects the document’s root element
:target#news:targetSelects the current active #news element (clicked on a URL containing that anchor name)
:validinput:validSelects all <input> elements with a valid value
:visiteda:visitedSelects all visited links

🔗 This is a great reading about CSS Selectors: The 30 CSS selectors you must memorize