Sub topic 1
Anatomy of a CSS Rule
Prerequisites
You should know basic HTML elements, attributes, and document structure. You should also know how to link a stylesheet and use simple CSS properties such as color and margin.
Anatomy of a CSS Rule
A CSS rule has a selector and a declaration block:
.card {
color: #222;
margin: 1rem;
}The selector, .card, chooses which HTML elements receive the styles. The declaration block is surrounded by braces. Each declaration contains a property, such as color, and a value, such as #222. A colon separates the property and value, and a semicolon ends the declaration.
flowchart LR
A[".card"] --> B["matches HTML elements"]
B --> C["declaration block"]
C --> D["color: #222"]
C --> E["margin: 1rem"]Type, Class, and ID Selectors
A type selector matches an element name:
p {
line-height: 1.5;
}A class selector starts with a period and matches an element's class attribute. Classes are reusable:
.note {
color: #555;
}<p class="note">This text is a note.</p>An ID selector starts with # and matches an element's id. An ID should identify one unique element in a document:
#main {
max-width: 60rem;
}<main id="main">Content</main>The Universal Selector
The universal selector, *, matches every element:
* {
box-sizing: border-box;
}It is useful for broad defaults, but avoid using it when a more precise selector expresses your intent.
Selecting by Attribute
An attribute selector matches elements based on an attribute:
a[target="_blank"] {
text-decoration: underline;
}This targets links whose target attribute equals _blank. Other forms can test whether an attribute exists or whether its value starts or ends with specific text.
Descendant, Child, and Sibling Combinators
Combinators describe relationships between elements:
article p { color: #333; } /* any descendant */
nav > a { padding: 0.5rem; } /* direct child */
h2 + p { margin-top: 0; } /* next sibling */A space matches any descendant. > matches only a direct child. + matches the immediately following sibling. These relationships let you target structure without adding more classes.
> callout note > Prefer classes for reusable component styles. Use IDs and structural selectors when the document relationship itself is the requirement.
Exercise
Which selector matches only links that are direct children of a nav element?
Show answer
nav > a