Explore CSS Selectors

Before getting started, Welcome you all in journey of learning CSS.

Now, we all know CSS is for styling and layout HTML elements. The question arises, How CSS identifies a HTML element to apply rules? Yes, we will explore that in this section. Let's get started!

What is CSS Selector?

The name itself clears everything. Selector selects something, but what does it select? Yes, you are correct! A HTML element.

How Selector identifies a HTML elements?

In this section, we will discuss common ways in which Selector targets/Selects a HTML element.

  • Using Element Type, Class Name, Id.

Type Selector - It selects element by it's tag name, like p, a etc.

p {                   
   color: white;        // CSS rule will be applied to all paragraphs
}

Class Selector - It selects element by it's class name preceded by a dot symbol.

.heading {               
   color: white;     // CSS rule will be applied elements with class *heading*
}

ID Selector - It selects element by it's id preceded by a hash symbol.

#quote {                  
   color: white;    // CSS rule will be applied elements with id *quote*
}

Note: Class and Id selector targets elements more specifically than Type selector, and hence given more priority, while resolving CSS conflicts.

  • Attribute Selector

This Selector refines our selection further using attributes and there values.

input [type='text'] {                     
  padding: 10px 15px;             // CSS rule will be applied input elements with type **text**
}
  • Pseudo Selectors

It selects elements on certain user events or element state like hover, active etc.

button:hover {                     
  background: transparent;      // CSS rule will be applied to all buttons when user hover on button element.
}
  • Selector List

Applies CSS rule to all selectors separated by comma. It is useful, when we need to apply same rule to set of different HTML elements.

h1, h2, p,  {                     
  color: white;      // CSS rule will be applied to all h1, h2 and p elements.
}
  • Combinator

Space combinator : To select an element, which is inside another element.

div h1 a  {                     
   color: white;        // CSS rule will be applied to anchor which is inside h1 and h1 is further inside div.
}

Child combinator : To select direct child of an element.

div > h1 {                     
  color: white;         // CSS rule will be applied to h1 which is direct child of div.
}

Sibling combinator: To select siblings of an element.

div ~ h4 {                     
  color: white;        // CSS rule will be applied to all h4 which are followed by p.
}

div + h4 {                     
  color: white;         // CSS rule will be applied to all h4 which is immediate followed by p.
}

References

developer.mozilla.org/en-US/docs/Learn/CSS/..