CSS Selectors Reference Guide

Element Selector

Applies to: All elements of the specified tag

Best used when: You want to style all instances of a element the same

Syntax: element { }

/* Styles all paragraph elements */
p {
  color: #333;
  line-height: 1.6;
  }

Group Selector

Applies to: Multiple elements specified separated by a comma

Best used when: You want to apply the same styles to several different elements

Syntax: element1, element2, element3 { }

/* Styles h1, h2, and h3 elements the same */
h1, h2, h3 {
  font-family: 'Arial', sans-serif;
  color: darkblue;
  }

Descendant Selector

Applies to: Elements that are descendants of a specified element

Best used when: You want to style elements when they appear inside certain elements

Syntax: ancestor descendant { }

/* Styles only paragraphs inside div elements */
div p {
  margin-left: 20px;
  }

Class Selector

Applies to: All elements with the specified class

Best used when: You want to apply styles to multiple elements with the same class

Syntax: .classname { }

/* Independent class selector */
.highlight {
  background-color: yellow;
  }

/* Dependent class selector */
p.highlight {
  font-weight: bold;
  }

ID Selector

Applies to: The single element with the specified id

Best used when: You need to style a unique element on the page

Syntax: #idname { }

/* Independent ID selector */
#main-header {
  text-align: center;
  }

/* Dependent ID selector */
div#main-header {
  border-bottom: 2px solid black;
  }

Universal Selector

Applies to: All elements on the page

Best used when: You want to apply a style to everything

Syntax: * { }

/* Applies to all elements */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  }

Pseudo Selectors

Applies to: Elements in a specific state

Best used when: You want to style elements based on user interaction

Syntax: selector:pseudo-class { }

/* Changes link color on hover */
a:hover {
  color: red;
  }

/* Styles every other table row */
tr:nth-child(even) {
  background-color: #f2f2f2;
  }

Pseudo Elements

Applies to: Specific parts of an element

Best used when: You want to style part of an element without adding extra HTML

Syntax: selector::pseudo-element { }

/* Adds content before paragraphs */
p::before {
  content: ">> ";
  color: blue;
  }

/* Styles the first line of paragraphs */
p::first-line {
  font-weight: bold;
  }

Selector Specificity Order

Specificity determines which CSS rule is applied when multiple rules conflict. Selectors with higher specificity override those with lower specificity.

Order Selector Type Specificity Level
1 Universal Selector (*) and combinators 0
2 Element Selectors and Pseudo-elements 1
3 Class Selectors, Attribute Selectors, and Pseudo-classes 10
4 ID Selectors 100
5 Inline Styles (style attribute) 1000

Note: The !important declaration overrides all specificity rules, but should be used sparingly as it can make CSS harder to maintain.