🌱BeginnerCSS Foundations

CSS Syntax and Selectors

Learn the anatomy of a CSS rule and the most common selector types: element, class, ID, attribute, and combinators.

Overview

A CSS rule has two parts: a selector and a declaration block. The selector targets which HTML elements to style; the declaration block contains one or more property-value pairs enclosed in curly braces. Selectors are how CSS finds elements. CSS provides many selector types so you can target exactly the elements you need: - **Element selectors** target all instances of a tag: `p`, `h1`, `div` - **Class selectors** target elements with a specific class attribute: `.card`, `.btn-primary` - **ID selectors** target one unique element: `#header`, `#main-nav` - **Attribute selectors** target elements based on their attributes: `[type="email"]` - **Combinator selectors** express relationships between elements: `article p` (descendant), `h1 + p` (adjacent sibling) Class selectors are the most commonly used they are reusable, composable, and do not carry the high specificity that causes ID selectors to be hard to override.

Key Points

  • •A CSS rule = selector + declaration block { property: value; }
  • •Element selectors target every instance of an HTML tag
  • •Class selectors (.) target elements with class="name" reusable across elements
  • •ID selectors (#) target a single unique element high specificity, use sparingly
  • •Multiple selectors separated by commas share the same declarations
  • •Descendant combinator (space) targets elements nested inside another

Examples

Element, class, and ID selectors

p { color: #333; }
.highlight { background-color: yellow; }
#logo { width: 120px; }

Classes start with a dot; IDs start with a hash.

Grouped and descendant selectors

h1, h2 { font-family: Georgia, serif; color: navy; }
nav a  { text-decoration: none; color: white; }
ul > li { list-style: square; }

Attribute selectors

input[type="email"] { border: 2px solid blue; }
[data-tooltip]      { cursor: help; }

Attribute selectors are powerful for styling form inputs by type.

Common Mistakes

  • Using an ID selector when a class would do IDs are very high specificity and hard to override
  • Forgetting the dot before a class name (.btn not btn)
  • Forgetting the hash before an ID name (#header not header)

Note

Prefer class selectors over ID selectors for styling. Keep IDs for JavaScript hooks (getElementById) and anchor links.

Exercises

Write CSS to style the HTML scaffold. The preview updates live — when it looks right, mark as done.

Loading editor…

Completed: 0 / 5 exercises

Knowledge Check

Question 1 of 4

Which selector targets an element with class="alert"?