CSS Syntax, Cascade, and Specificity
CSS controls how HTML appears. It can change color, spacing, borders, positioning, and layout. But CSS is not simply "decorating" a page. It is a rule system.
A CSS rule has:
- a selector
- one or more declarations
h1 {
color: navy;
margin-bottom: 16px;
}
The browser follows the cascade, meaning multiple rules may target the same element. When that happens, CSS decides which rule wins based on:
- specificity,
- source order,
- and importance.
Specificity usually follows this logic:
- element selectors are weaker,
- class selectors are stronger,
- ID selectors are stronger than classes.
Example:
p { color: black; }
.notice { color: blue; }
#mainNotice { color: red; }
If the same paragraph matches all three, the ID selector usually wins.
Understanding the cascade is important because many CSS errors are not syntax errors. They are selection errors. The style exists, but the wrong rule is taking priority.
The Box Model and Modern Layout
Every visible HTML element behaves like a box. The CSS box model includes:
- content
- padding
- border
- margin
This explains why elements take up more space than the raw width or height you assign.
Example:
.card {
width: 300px;
padding: 20px;
border: 1px solid #333;
margin: 10px;
}
This element uses more horizontal space than 300px because padding and border add to it.
For layout, older approaches relied heavily on floats or tables. Modern CSS favors:
- Flexbox for one-dimensional layout
- Grid for two-dimensional layout
Use Flexbox when arranging items in a row or column, such as navigation links or cards. Use Grid when building larger page sections, such as dashboards or gallery structures.
.container {
display: flex;
gap: 16px;
}
This creates a far cleaner layout than manually forcing positions.
Responsive Design and Mobile-First Thinking
ProReviewer — locked
Drills, code labs, and full solutions.
Visual Consistency and Basic UI Decisions
ProReviewer — locked
Drills, code labs, and full solutions.
Practice & Exam Drills — Lesson 3
ProReviewer — locked
Drills, code labs, and full solutions.