CSS selectors

Code on a screen

Notes on what I learned from video “CSS Selectors” from the The Complete Web Developer in 2018: Zero to Mastery class on Udemy


What are CSS selectors and why should I care?

CSS selectors are the part of CSS that actually select the part of the html code that you want to apply style to. In order to change something with CSS, you need to know what selector to use to grab the thing you want to change!


element1, element2      Applies style to both elements

element1 element2       Applies style to all element2s that are within element1s (for example, if it was ‘p li’, it would apply the style to all lists that are within paragraphs.


element1 > element2    Applies style to all element2s that are parents of element1s

Example:

html:

<h2>My thoughts on CSS</h2>
<div>
<p>CSS is really cool.
</div>

css:

h2 > p {
      color: #AA4139;
}


In this example, the CSS style will not be applied because div (not h2) is the parent of p. If we wanted the code to apply to p, we would need to change h2 > p to div > p



.class       
Can be used to apply style to a subset of an element. Can be applied multiple times throughout the html document.

Example:

html:

<p class=”exampleclass”>Example paragraph would be red.</p>
<p class=”exampleclass”>Example paragraph would be red.</p>
<p class=”exampleclass extra”>Example paragraph would be purple.</p>

css:

.exampleclass {
      color: red;
}

.extra {
      color: purple;
}


#id        Similar to class, but can be used only once throughout the html document.

Example:

html:

<div id=”div1″>Example would be blue</div>

css:

#div1 {
      background: blue;
}


*       Applies style to everything (unless the element has been overridden with another selector)


:hover 
  Applies style to the element(s) on mouse hover

css:

h2, p:hover {
      color: red;
}


.webtext:last-child     
Applies style to the last child of the set

.webtext:first-child    Applies style to the first child of the set


!important    Will override ALL other formatting (use not recommended)

Example:

html:

<p>This paragraph will be pink, despite the last selector indicating that it should be blue.</p>

css:

p {
      color: pink !important;
}

p {
      color: blue;
}


What selectors win out in the cascade depends on:

  • Specificity (higher specificity given priority)
  • Importance
  • Source Order

Click here for a cool Specificity calculator!