Complete 2024 Web Development Bootcamp

Dr. Angela Yu

Back to CSS Index Page


 

CSS Selectors
Intro

To assign styles to html elements we need to be able to "select" the relevant elements. We do this with CSS Selectors.

Selectors
  • Attribute Selector []
    • A Way to specifically target an element's attribute. Attributes are things such as ID, or Class, or "draggable". If we had one, (or more) <p> element(s) with an ID of "priority":
      • <p id="priority">This paragraph has priority</p>
      then
      • p[#priority] {}
      would select all of the <p> elements, with an ID of "priority".
  • Group Selector , (comma)
    • Allows us to target multiple elements. If we have an <h1> and an <h2> element that we want to select, we would use:
      • h1, h2 {}
      This would group both elements for styling.
  • Direct Descendant, or Child Selector > (greater than)
    • Allows us to select all descendant element(s), that are a direct descendant. If we had a <div> with descendant <p> element(s), we could select the descendants, like so:
      • div > p {}
      This would select all <p> elements, that are direct descendants to a <div> element (but only direct descendants one level down).
  • All Descendant Selector   (space)
    • Selects ALL of the descendant elements specified, of the parent element. So, if we have a <div> element, and inside are a couple of <p> elements, and a <ul> with a <p> element, if we select:
      • div (space) p {}
      This would select ALL of the <p> elements nested anywhere within the parent <div> element.
  • Chaining
    • Chaining is a way of being very specific in our element selection process. Let's say we have an <h1> with an ID of title, and two classes (class1, & class2):
      • <h1 id="title" class="class1 class2">
      We could be very specific in targeting this <h1> by using:
      • h1#title.class1.class2
      This is the essence of "chaining". We are selecting an <h1> with an ID of title, a class of class1 and a class of class2. Notice that there are NO Separations between the element, id, and both classes. It is all "chained" together into one long selector.


Back to Top