CSS Selectors

Selectors in CSS are used to target HTML elements and apply styles to them. A selector defines which element(s) the CSS rule will affect.

1) Element Selector


p {
  color: blue;
}

This selects all <p> elements and makes the text blue.

2) ID Selector


#intro {
  font-size: 18px;
}

Selects the element with id="intro".

3) Class Selector


.note {
  background-color: yellow;
}

Selects all elements with class="note".

4) Universal Selector


* {
  margin: 0;
  padding: 0;
}

Applies style to all elements on the page.

5) Grouping Selector


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

Applies the same style to multiple elements at once.

6) Descendant Selector


div p {
  color: green;
}

Targets <p> inside a <div>.

7) Child Selector


div > p {
  font-weight: bold;
}

Targets only <p> elements that are direct children of <div>.

8) Pseudo-class Selector


a:hover {
  color: red;
}

Applies styles when the user hovers over a link.

Quick Notes:

  • #id → unique element
  • .class → multiple elements
  • element → all such elements
  • * → everything
  • Pseudo-classes like :hover, :first-child, :nth-child() allow dynamic styling.