CSS Basics
Selectors, the cascade, the box model, colors and typography.
What you will learn
- Write selectors
- Explain specificity
- Use the box model
CSS (Cascading Style Sheets) controls how HTML looks: colors, fonts, spacing and layout. A rule has a selector (what to style) and declarations (how to style it).
h1 {
color: #0a0a0a;
font-size: 2rem;
}Link a stylesheet from the head of your page: <link rel="stylesheet" href="styles.css">.
p { } /* every paragraph */
.card { } /* elements with class="card" */
#hero { } /* the element with id="hero" */
nav a { } /* links inside nav */
ul > li { } /* direct children only */
a:hover { } /* when hovered */
input:focus-visible { } /* keyboard focus */
button[disabled] { } /* attribute selector */Prefer classes for styling. IDs are too specific, and element selectors are too broad.
The cascade and specificity
When rules conflict, CSS picks a winner: the more specific selector wins (ID beats class beats element), and if specificity is equal, the rule that comes later wins. Some properties are also inherited by children, such as color and font-family. Avoid !important; it makes styles hard to override and debug.
The box model
Every element is a box made of content, padding (space inside), border and margin (space outside). By default, width covers only the content, so adding padding makes the box larger. Almost every stylesheet begins by fixing that:
*, *::before, *::after {
box-sizing: border-box; /* width includes padding and border */
}
.card {
width: 300px;
padding: 1rem;
border: 1px solid #ddd;
border-radius: 8px;
margin: 0 auto 1.5rem;
}Units and colors
px: fixed pixels.rem: relative to the root font size (great for accessible sizing).em: relative to the current font size.%,vw,vh: relative to the parent or the viewport.- Colors: names (
tomato), hex (#ff6347),rgb(),hsl().
body {
font-family: system-ui, -apple-system, "Segoe UI", sans-serif;
font-size: 1rem;
line-height: 1.6;
color: #222;
}
h1 { font-weight: 700; letter-spacing: -0.02em; }Custom properties
CSS variables keep values consistent and make theming easy.
:root {
--brand: #2563eb;
--radius: 8px;
}
.button {
background: var(--brand);
border-radius: var(--radius);
color: white;
padding: 0.6rem 1.2rem;
}
.button:hover { filter: brightness(1.1); }Right-click an element and choose Inspect. You can see which rules apply, which are overridden, and edit values live. It is the fastest way to learn CSS.
Try it yourself
Style a card: a white background, 1rem padding, a subtle border, rounded corners and a hover effect that lifts it with a shadow.
Show solution
.card {
background: #fff;
padding: 1rem;
border: 1px solid #e5e5e5;
border-radius: 10px;
transition: box-shadow 0.2s, transform 0.2s;
}
.card:hover {
box-shadow: 0 8px 20px rgba(0, 0, 0, 0.08);
transform: translateY(-2px);
}