CSS Fundamentals: Selectors, the Cascade and the Box Model
Writing rules
selector {
property: value;
}
.card {
padding: 16px;
border: 1px solid #e5e7eb;
border-radius: 12px;
}
Selectors
p { } /* every <p> */
.card { } /* class */
#site-header { } /* id (avoid for styling: too specific) */
nav a { } /* <a> inside <nav> */
.menu > li { } /* direct children */
a:hover, a:focus-visible { } /* states */
input[type="email"] { } /* attribute */
li:first-child { } li:nth-child(odd) { }
.card::before { } /* generated content */
Style mostly with classes. They are reusable and keep specificity low.
The cascade: which rule wins?
- Importance (
!importantbeats normal; avoid it). - Specificity: id (1,0,0) > class/attribute/pseudo-class (0,1,0) > element (0,0,1).
- Order: later rules win when specificity ties.
.button { background: blue; }
a.button { background: green; } /* wins: higher specificity */
Most "my CSS does not work" problems are specificity. DevTools (Elements → Styles) shows crossed-out rules and which rule won.
The box model
Every element is a box: content → padding → border → margin.
*, *::before, *::after { box-sizing: border-box; }
With border-box, width: 300px includes padding and border, which is far easier to reason about. Put this reset at the top of every project.
Units
| Unit | Relative to | Use for |
|---|---|---|
px |
fixed | borders, small details |
rem |
root font size | font sizes, spacing |
% |
parent | widths |
vw / vh |
viewport | full-screen sections |
ch |
character width | readable line length (max-width: 65ch) |
clamp(min, preferred, max) makes fluid sizes: font-size: clamp(2rem, 5vw, 3.5rem).
Colors and custom properties
:root {
--brand: #7c3aed;
--text: #0f172a;
--radius: 12px;
}
.button { background: var(--brand); border-radius: var(--radius); }
Custom properties (CSS variables) make themes and dark mode easy: change them in one place.
Display
block: takes full width, starts a new line (div,p).inline: flows in text (span,a); width/height ignored.inline-block: inline but accepts size.none: removed from layout.flexandgrid: the layout systems of the next modules.
Exercise
Style the bakery page: a CSS reset with box-sizing, custom properties for colours, readable body text (max-width: 65ch, line-height: 1.6) and styled product cards. Use DevTools to inspect each card's box model.
Check yourself
- Which wins:
#nav aor.nav-link? - What does
box-sizing: border-boxchange? - Why use
remfor font sizes?
يُحفظ تقدّمك في هذا المتصفح فقط.
إرسال للمراجعة (10 نقطة)