DEV Community

Aditya Pratap
Aditya Pratap

Posted on

CSS Selectors

Selectors in CSS are a way to style specific parts of your web page that could be either whole document, a single element or multiple.

THE NEED

Suppose a pool of people, you only wanna email people of age group 21-24, how will you move on. You can not just bombard some mails randomly or share them to everyone, there is a specific case. First, you will filter out the data and then proceed with the emails after filtering the correct ones out. That's just how CSS Selectors help.

Let's checkout some CSS Selectors:

  • Element Selector

It targets all elements of a specific type.

<p>This is a paragraph.</p>
<p>This is another paragraph.</p>

p {
  color: blue;
}

# All <p> elements turn blue.
Enter fullscreen mode Exit fullscreen mode
  • Class Selector

Classes let you couple multiple elements as per convenience and style them.

<p class="highlight">Important text!</p>
<span class="highlight">Notice me too!</span>

.highlight {
  background-color: yellow;
}

# Both the paragraph and span get a yellow background.
Enter fullscreen mode Exit fullscreen mode
  • ID Selector

ID selector allows targeting single element with their HTML id.

<h2 id="main-title">Welcome!</h2>
<h2> Platform Features </h2>

#main-title {
  font-size: 36px;
  color: darkgreen;
}

# H2 element with id="main-title" is styled.
Enter fullscreen mode Exit fullscreen mode
  • Group Selectors

It's possible to target multiple HTML elements by grouping them.

h1, h2, h3 {
  font-family: 'Arial', sans-serif;
  color: navy;
}

# All headings from <h1> to <h3> get the same font and color.
Enter fullscreen mode Exit fullscreen mode
  • Descendant Selectors Descendant selectors allow you target elements nested inside other elements.
<div class="card">
  <p>This is inside a card.</p>
</div>

<p>This is outside the card.</p>

.card p {
  color: red;
}

# Only the paragraph inside .card turns red.
Enter fullscreen mode Exit fullscreen mode
  • Universal Selector Allows targeting complete web page.
* {
  font-family: 'Arial', sans-serif;
  color: navy;
}

# Complete page's font is styled.
Enter fullscreen mode Exit fullscreen mode

Selectors Specificity

At time multiple selectors can target the same element.

p {
  color: blue;
}

.highlight {
  color: green;
}

#main-text {
  color: red;
}
Enter fullscreen mode Exit fullscreen mode

In this case, CSS cascades over and over with the utmost priority given on how specific this selector is.

  • ID selector (#id) → highest priority

  • Class selector (.class) → medium priority

  • Element selector (element) → low priority

Top comments (0)