NelsonLabs
CSS Styling/Selectors & Specificity

Selectors & Specificity

Selectors are the targeting system of CSS. They determine which HTML elements your styles apply to. Getting selectors right is the difference between clean, maintainable CSS and a tangled mess.

Basic selectors

Element, class, and ID selectors
css
/* Element selector โ€” targets every <p> on the page */
p {
  line-height: 1.8;
}

/* Class selector โ€” targets any element with class="card" */
.card {
  background: #201D15;
  border: 1px solid #2E2A22;
  border-radius: 8px;
  padding: 1.5rem;
}

/* ID selector โ€” targets the single element with id="hero" */
#hero {
  min-height: 90vh;
  display: flex;
  align-items: center;
}

/* Multiple elements โ€” comma separates selectors */
h1, h2, h3 {
  font-weight: 700;
  letter-spacing: -0.02em;
}

Combinators โ€” selecting by relationship

Combinator selectors
css
/* Descendant โ€” any <p> anywhere inside .content */
.content p {
  color: #998870;
}

/* Child โ€” only direct children */
.nav > li {
  display: inline-block;
}

/* Adjacent sibling โ€” the first <p> immediately after an <h2> */
h2 + p {
  margin-top: 0;
  font-size: 1.1rem;
}

/* General sibling โ€” all <p> after an <h2> in the same parent */
h2 ~ p {
  color: #998870;
}

Pseudo-classes and pseudo-elements

Pseudo-classes and pseudo-elements
css
/* Pseudo-classes โ€” element states */
a:hover     { color: #C96A30; }           /* mouse over */
a:focus     { outline: 2px solid #C96A30; } /* keyboard focus */
input:valid { border-color: #4A8C60; }    /* valid form input */

button:active { transform: scale(0.98); } /* clicked */

li:first-child { font-weight: bold; }     /* first item */
li:last-child  { border-bottom: none; }   /* last item */
li:nth-child(2n) { background: #201D15; } /* every even item */

/* Pseudo-elements โ€” style parts of elements */
p::first-line  { font-weight: 600; }
p::first-letter { font-size: 2em; float: left; }

/* Add content before/after without changing HTML */
.required::after {
  content: ' *';
  color: red;
}

Specificity โ€” which rule wins?

ANALOGY

A points system. When multiple CSS rules target the same element, the browser calculates a specificity score for each. Inline styles score highest, then ID selectors, then class selectors, then element selectors. Higher score wins โ€” regardless of which rule appears last in the file.

Selector typeSpecificity valueExample
Inline style1000style="color: red"
ID100#header
Class / pseudo-class / attribute10.card :hover [type='text']
Element / pseudo-element1p h1 ::before
Universal / combinators0* > + ~