Skip to main content

Command Palette

Search for a command to run...

CSS Selectors 101: Targeting Elements with Precision

Learn CSS Selectors: A Guide to Targeting Elements Precisely

Published
2 min read

Why CSS selectors are needed?

CSS Selector: This selector is used to select one ore more element to which we want top apply the style.

Basic syntax of CSS Selector:

selctor{
    property-1: value-1;
    property-2: value-2;
}

Why its needed?

  • Applying style: This allows a developer to apply style like color, format, background, layout to a specific element.

  • Efficiency and reusability: Adding inline style to every HTML page may result in a confusion and it can be time taking. But CSS uses selector to apply style to various elements simultaneously.

  • This helps in maintaining a difference between HTML web structure and Visuals by maintaining a separate CSS file this ensures clean and readability.

Class Selector in CSS

Class selector is used when we want to style more than one element in HTML simultaneously.

Example:

<h1 class = "xyz"> Heading One </h1>
<p class = "xyz"> Paragraph </p>
.xyz{
    property-1: value-1;
    property-2: value-2;
 }

ID Selector in CSS

  • The CSS ID selector (#) is used to select a single, unique HTML element on a webpage based on its id attribute

  • It allows developers to apply specific styles to one particular element, such as a header or a footer.

<footer>
    <p id="abc"> All Rights Reserved </p>
</footer>
#unique-element-id {
  color: blue;
  border: 1px solid black;
}

Group selector in CSS

This selector helps in applying same type of style to multiple different element just by doing a single declaration instead of declaring you can you can do this:

  selector1, selector2, selector3 {
  color: blue;
  text-align: center;
}

Descendant selector in CSS

This selector works in such way it selects any element inside another element, no matter how deep it is.

<div>
  <p>This paragraph is inside div (selected)</p>

  <section>
    <p>This paragraph is deeper inside div (also selected)</p>
  </section>
</div>

<p>This paragraph is outside div (NOT selected)</p>
div p {
  color: red;
}

This means:
All <p> elements inside a <div> will become red —
even if the <p> is inside another element like a <section>.

CSS Selector Specificity

It is a type of priority order which determines the higher priority and lower priority. For Example if two different selector applied to an element higher specific will override the lower specific.