Unit 6 · Cascading Style Sheets (CSS)

6.4CSS Selectors

SelectorSyntaxSelects
Universal* { }Every element
Element (type)p { }All <p> elements
Class.note { }Elements with class='note' (reusable)
ID#header { }The one element with id='header' (unique per page)
Grouph1, h2, p { }Several selectors sharing one rule
HTML
<h1 id='title'>Shop</h1>
<p class='note'>Free delivery</p>
<p class='note urgent'>Ends today</p>  <!-- an element can have several classes -->
CSS
* { margin: 0; padding: 0; }
#title { color: navy; }
.note { background: #fff3cd; padding: 8px; }
.note.urgent { color: red; }      /* both classes on the same element, no space */
h1, h2, h3 { font-family: Arial, sans-serif; }

Combinators (relationships between elements)

SelectorMeaning
div pAny p inside a div (descendant)
div > pp that is a direct child of div
h1 + pThe p immediately after an h1
h1 ~ pAll p siblings after an h1

Attribute selectors: input[type='text'] { }, a[href^='https'] { } (starts with).

Specificity (highest wins): inline style, then ID, then class/attribute/pseudo-class, then element. Example: #title beats .note beats p. Avoid !important unless essential.

inline stylestyle='color: red'ID selector#titleclass, attribute, pseudo-class.note [type='text'] :hoverelement, pseudo-elementp h1 ::beforestronger ↑
Specificity: when two rules conflict, the more specific selector wins (#title beats .note beats p)

Nesting CSS

Modern CSS lets you write a rule inside another so related styles stay together and you do not repeat the parent selector. It is supported in current browsers.

CSS
.card {
  padding: 16px;
  border: 1px solid #ccc;

  h2 { color: navy; }            /* same as .card h2 */
  p  { line-height: 1.6; }       /* same as .card p */

  &:hover { box-shadow: 0 4px 10px rgba(0,0,0,.2); }  /* & means .card itself */
  &.featured { border-color: gold; }                  /* .card.featured */
}

Sass and Less (tools that compile to CSS) offered nesting for years; native CSS nesting now does the same job without tools.