DEV Community

Priyanshu verma
Priyanshu verma

Posted on

CSS Selectors

Why Do We Need CSS Selectors?

CSS is used to make a website look good. But CSS first needs to know which HTML element to style.

That is why we use CSS selectors.

Selectors help CSS choose elements on a webpage.

Think of selectors like calling people by name:

  • Calling "Everyone" → all people respond
  • Calling "People in blue shirts" → only a group responds
  • Calling "Rahul" → one person responds

CSS works the same way.

Element Selector

The element selector selects elements by their HTML tag name.

p {
  color: blue;
}
Enter fullscreen mode Exit fullscreen mode

This will change the color of all paragraphs.

Use element selectors when:

  • You want to style all same elements
  • You need simple and global styling

Class Selector

A class selector selects elements using a class name.

Class selectors start with a dot (.).

HTML:

<p class="note">This is important</p>
Enter fullscreen mode Exit fullscreen mode

CSS:

.note {
  color: red;
}
Enter fullscreen mode Exit fullscreen mode

Class selectors are:

  • Reusable
  • Very common
  • Flexible

You can use the same class on many elements.

ID Selector

An ID selector selects one unique element.

ID selectors start with a hash (#).

HTML:

<h1 id="title">Welcome</h1>
Enter fullscreen mode Exit fullscreen mode

CSS:

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

Rules for ID:

  • Used only once
  • Not reusable

Group Selector

Group selectors let you style many elements at once.

h1, h2, p {
  font-family: Arial;
}
Enter fullscreen mode Exit fullscreen mode

This saves time and keeps CSS clean.

Descendant Selector

A descendant selector selects elements inside another element.

div p {
  color: purple;
}
Enter fullscreen mode Exit fullscreen mode

This means:

  • Select <p>
  • Only if it is inside <div>

Basic Selector Priority

Sometimes more than one selector styles the same element.

Who wins?

  1. ID selector (strongest)
  2. Class selector
  3. Element selector (weakest)

The stronger selector is applied.

Top comments (0)