Codectionary / Developer documentation / CSS

Basic Selectors

CSS selectors target elements to style. Type selectors match by tag name, class selectors (.name) match elements with that class, ID selectors (#name) match a single unique element, and the universal selector (*) matches everything. Classes are the most commonly used selector for reusable styling.

Syntax

element { }
.class { }
#id { }
* { }

Examples

The Four Basic Types

Type, class, ID, and universal selectors.

p { color: #333; }              /* every <p> element */
.highlight { background: yellow; } /* every element with class="highlight" */
#main-header { font-size: 2rem; }  /* the single element with id="main-header" */
* { box-sizing: border-box; }       /* every element on the page */

Combining Selectors

Selectors can be combined for more specific targeting.

p.intro { font-weight: bold; }   /* only <p> elements that ALSO have class="intro" */
.card.featured { border: 2px solid gold; } /* elements with BOTH classes */

Parameters and values

  • element (type selector): Matches all elements of that tag name
  • .class (class selector): Matches all elements with that class
  • #id (ID selector): Matches the single element with that id
  • * (universal selector): Matches every element

Best practices

  • Prefer classes over IDs for styling - classes are reusable across multiple elements, while IDs must be unique per page and carry high specificity that is hard to override
  • Avoid styling directly by element type (like p or div) in larger projects, since it applies globally and is easy to accidentally affect unrelated content
  • Use the universal selector (*) sparingly, typically just for resets like box-sizing, since it applies to literally everything
  • Combine class selectors (.card.featured) rather than deeply nesting selectors, for flatter, more maintainable specificity

At a glance

Purpose
Presentation and layout
File extension
.css
Runs in
Web browsers
Usually used with
HTML and JavaScript

Specifications & further reading

Related CSS documentation