Lesson 2 of 9

Selectors & Properties

You'll learn how selectors choose which elements to style, and how specificity decides which rule wins when two rules conflict.

/* Element selectors */
p { color: #333; }
h1 { font-size: 2rem; }

/* Class selector — use for reusable styles */
.highlight { background-color: yellow; }
.btn { padding: 8px 16px; border-radius: 4px; }

/* ID selector — use for unique elements */
#header { position: fixed; top: 0; width: 100%; }

/* Attribute selector */
input[type="email"] { border: 2px solid blue; }
a[href^="https"] { color: green; }  /* href starts with "https" */
a[href$=".pdf"] { color: red; }     /* href ends with ".pdf" */

/* Pseudo-classes — element in a specific state */
a:hover { text-decoration: underline; }   /* mouse over */
input:focus { outline: 2px solid blue; }  /* keyboard focused */
li:first-child { font-weight: bold; }
li:last-child { color: gray; }
li:nth-child(odd) { background: #f0f0f0; }
p:not(.intro) { font-size: 0.9rem; }

/* Pseudo-elements — virtual elements */
p::first-line { font-weight: bold; }
p::first-letter { font-size: 2em; }
.quote::before { content: '"'; }
.quote::after { content: '"'; }

/* Combinators */
div p { color: blue; }        /* descendant: any p inside div */
div > p { color: red; }       /* child: direct p children of div */
h1 + p { margin-top: 0; }    /* adjacent sibling: p immediately after h1 */
h1 ~ p { color: gray; }       /* general sibling: any p after h1 */

/* Multiple selectors */
h1, h2, h3 { font-family: serif; }
CSS on a sample page

specificity determines which rule wins when multiple rules target the same element. ID selectors beat selectors, which beat element selectors. When specificity is equal, the last rule in the stylesheet wins.

/* Common text properties */
.text-demo {
  font-family: 'Arial', Helvetica, sans-serif; /* fallback chain */
  font-size: 1rem;          /* 1rem = 16px by default */
  font-weight: bold;         /* or: 100-900, or: normal */
  font-style: italic;
  line-height: 1.5;          /* spacing between lines */
  letter-spacing: 0.05em;    /* spacing between letters */
  text-align: center;        /* left, right, center, justify */
  text-transform: uppercase; /* lowercase, capitalize */
  text-decoration: underline; /* none, overline, line-through */
  color: #333333;
}

/* Common color formats */
.colors {
  color: red;                 /* named color */
  color: #ff0000;             /* hex */
  color: rgb(255, 0, 0);      /* rgb */
  color: rgba(255, 0, 0, 0.5); /* rgba with alpha */
  color: hsl(0, 100%, 50%);   /* hue, saturation, lightness */
  color: oklch(0.6 0.2 30);   /* oklch (modern, perceptually uniform) */
}
CSS on a sample page
Finished reading?Mark it done to track your progress.

Tip: use the ← and → keys to move between lessons.