DEV Community

Cover image for CSS Selectors 101: Targeting Elements with Precision
Anoop Rajoriya
Anoop Rajoriya

Posted on

CSS Selectors 101: Targeting Elements with Precision

Introduction

Understanding, How to precisely select HTML elemtn is criticle concept for every frontend developer. These article provide you a good knowledge about What are selectors and How to use them to select elements with precision.

Content List

What CSS Selectors & Why Need It

Selectors are patterns alow pointing HTML element from the CSS code. This pointing enable to apply styles to specific or group of elements. The selectors are the fundamental concept used in CSS without these its hard to apply styles efficiently. Selectors enable to create complex and interactive layouts, applying consistant styles across entire page, help to seperate styles to HTML which make code more readable.

If There multiple rules are defined for the same HTML elements the browser determin which one wins by using the rules called Cascading (means styles read later by browser is that one get applied) & Specificity (rules prioritize styles).

Basics CSS Selectors

These are the foundation selectors which provide a very straightforword way to select HTML elements. It include four major selectors Universal Selector, Element Selectors, Id Selectors, and Class Selectors.

1: Universal Selector

The universal selector used to select every element a HTML page contain. It mostly used to apply test styles quickly on a entire page. It implemented by using * symbol. This selector recomandade to not use it in production because it push weight on browser and affact performance.

*{
    padding: 0;
    margin: 0;
    box-sizing: border-box;
    font-family: 'Arial', sans-serif;
    color: red;
}
Enter fullscreen mode Exit fullscreen mode

universal selector

2: Element Selectors

Element selector used to select any HTML element by using their tag name. When you apply some style to element by using element selector remember it apply given style to every element that tag name used as selector.

p {
  color: red;
}

h2 {
  color: blue;
  text-transform: uppercase;
  border-bottom: 2px solid;
}
Enter fullscreen mode Exit fullscreen mode

element selector

3: Id Selectors

Id selector use HTML id name provided to element which uniquly identified it within entire page. It implemented by using # symbol with the following id name of element. It mostly used to targeting unique element for applying specific styles.

#main-header {
    background-color: #f4f4f4;
    padding: 40px;
    text-align: center;
    border-radius: 8px;
}
Enter fullscreen mode Exit fullscreen mode

id selector

4: Class Selectors

This selector use class attribute name to target elements in HTML page. It use . dot symobe along with the class name. It mostly used to select group of elements to apply same type styles, its a common standard in web-dev.

.subtitle {
  font-style: italic;
  color: #555;
  margin-top: 20px;
}
Enter fullscreen mode Exit fullscreen mode

class selector

Combined CSS Selectors

Combined selectors are the high level selecors these selectors are implement with the help of basics selectors. Majorly used combined selecors are Grouped Selector, Chained Selector, Descendants Child Selector, Direct Child Selector, Adjacent Sibling Selector, and General Sibling Selector

1: Grouped Selector

Grouped selectors are used to target multiple elements with different type selectors. It implement those by writing basics selectors and separating them with , comma. It mostly used to reduce redundant styles by grouping them.

h1, h2, h3 {
  font-family: 'Helvetica', sans-serif;
  color: darkblue;
  letter-spacing: -1px;
}
Enter fullscreen mode Exit fullscreen mode

grouped selector

2: Chained Selector

It is defined by writing multiple selectors wihout any spaces between them. It target element only if it has all these qulifires at the same time. It also a good way to narrow down the targeting view.

.footer-note.important {
  background-color: #fff566;
  border: 1px solid #ffeeba;
  font-weight: bold;
  padding-inline: 12px;
  padding-block: 8px;
  margin-block: 6px;
}
Enter fullscreen mode Exit fullscreen mode

chained selector

3: Descendants Child Selector

It implemented by just writing selectors by seperating spaces. It used when you want to select all perticular y elements inside of another x element. Ensure y do not have to be direct childe of x elements.

.parent-box p {
  color: blue;
  text-decoration: underline;
}
Enter fullscreen mode Exit fullscreen mode

descendant child selector

4: Direct Child Selector

It use > symbol to target direct childs of elements. It target all direct y elements of the another elements x, here it only target all y elements those are a direct childes of x elements.

.parent-box > p {
  background-color: #d1ecf1;
  padding: 5px;
}
Enter fullscreen mode Exit fullscreen mode

direct child selector

5: Adjacent Sibling Selector

It used when you want to apply styles to a element that comes just after the another element. You write a selector targeting a element, than + plus symbol, and than writing a selector that targeting element want to apply style on that.

h3 + p {
  color: #8e44ad;
  font-weight: 700;
  font-size: 1.1rem;
}
Enter fullscreen mode Exit fullscreen mode

adjacent sibling selector

6: General Sibling Selector

Just like a adjacent sibling selector its also use to select siblings but it select all the siblings of an element. First write selector of element x and ~ symbol, than write another selecor which target all the elements y those come after the x element.

h3 ~ p {
  color: white;
  background-color: #333;
  padding-left: 14px;
}
Enter fullscreen mode Exit fullscreen mode

general sibling selectors

Selector Priority (Specificity)

In starting we have discussesd about how CSS styles applied to elements it used Cascading (we already disscueesed in starting) and Specificity rules:

Specificty is like a weight system a browser use to identified which rule win when multiple styles applyied on element. Think it like a scoring system, when more specific selector is the higher score it get. We can assure in the specificity hierarchy each selector have a specificty score which determins its priority:

  1. Inline styles have a 1000 most higher priority score which is higher than others.
  2. ID Selectors have a 0100 second higher priority scores.
  3. Class Selectors have a 0010 third higher priority scores.
  4. Element Selectors have a 0001 least higher priority scores.

Based on these scores we can determine which style rule wins. Lets see an example which clearify the specificity rules:

We have a three different styles rule with different selectors:

/*<p id="intro" class="highlight">Hello World</p>*/

p{
    color: red;
}

.highlight{
    color: blue
}

#intro{
    color: green;
}
Enter fullscreen mode Exit fullscreen mode

Think which style wins and apply color to paragraph element. If your answer is green you nailed it, its right answer. Lets see score calculation:

Here element selector style get score 0001, class selector get 0010, and id selector get 0100. To seeing all that we figured the higher score is 0100 so here id selector wins.

What if there are multiple styles rule those have same specificity?
Than here the cascading rules decides the result, in same case if specificity apears than styles rules wins which apears in last.

targeting element with precision and class vs Ids in css


Summary

CSS selectors function as a foundational pattern-matching system that dictates how styles are targeted and prioritized through a weighted scoring mechanism known as specificity.

  • Understanding CSS selectors and cascading.
  • Basics CSS selectors.
  • Combined CSS selectors.
  • Selector priority (Specificity) scores.

To maintain a maintable code prioritize use of classes and ids for reusabilty, readability in large projects and separation of concerns.


Top comments (0)