Why this matters
HTML says what content is; CSS says how it should appear. Without CSS a browser still shows your page, but it uses its own plain default styling. Learning CSS lets you take control of layout, colour, spacing, and typography so your page looks intentional on every screen size.
CSS also saves an enormous amount of repetition. One rule can style thousands of elements, and a single design token changed in one place can update an entire site. That combination of reach and economy is why CSS remains essential no matter which framework or build tool you use.
CSS is also declarative, which takes some getting used to if you are coming from a programming language. You describe the outcome and let the browser compute the result, so there is no step-by-step procedure to debug. Once you accept that, the cascade stops feeling arbitrary and starts feeling like a predictable set of priorities.
The big picture
A stylesheet is a list of rules. Each rule has a selector that picks elements and a declaration block that sets properties to values. The browser matches selectors against the DOM tree, resolves conflicts between rules, and applies the winning values. Everything flows from that simple loop.
Two ideas explain most surprises. The cascade decides which rule wins when several match, and the box model decides how much space an element occupies. Once you can predict both, CSS becomes a system of small, composable decisions rather than a bag of tricks.
A useful mental model is to imagine every element arriving with a default set of declarations from the browser stylesheet. Your rules are layered on top, and later or more specific declarations replace earlier ones. Even layout follows from this: changing display changes how a box participates in its parent's layout algorithm.
Core ideas
Selectors
A selector tells the browser which elements a rule targets. Type selectors match tag names, class selectors match the class attribute, and id selectors match one unique id. Combining them with child and descendant combinators lets you target very specific parts of a page.
Pseudo-classes such as hover and focus match elements in a particular state, while pseudo-elements such as before target a position. Attribute selectors match on attributes and their values. Good selectors are specific enough to hit the right elements but simple enough to stay readable.
p { color: #333; }
.card > h2 { margin: 0; }
a:hover { text-decoration: underline; }
input[type="email"] { border: 1px solid #bbb; }
Watch out. Stacking many classes to force a match. Prefer a single descriptive class over a long fragile selector chain.
The box model
Every element is a rectangular box. From the inside out it has content, padding, a border, and a margin. Padding sits inside the border and adds space around the content; margin sits outside and separates the element from its neighbours.
By default width applies to the content only, so padding and border make an element wider than you expect. Setting box-sizing to border-box makes width include padding and border, which is far easier to reason about. Most resets apply it globally for that reason.
.box {
width: 200px;
padding: 16px;
border: 2px solid #333;
margin: 8px;
box-sizing: border-box;
}
Watch out. Forgetting border-box and wondering why two 50 percent columns wrap onto separate lines.
Cascade and specificity
When several rules set the same property, the browser chooses one. Source order matters, so later rules override earlier ones when specificity is equal. Inheritance lets children pick up values such as color and font from their ancestors, which is why setting a font on body affects the whole page.
Specificity is a ranking: an id beats a class, and a class beats a type selector. Inline styles beat all of them, and an important declaration beats almost anything. Keeping specificity low avoids fights, so lean on classes and source order instead of piling on ids.
Cascade layers, written with the layer at-rule, give you explicit control over groups of rules. A rule in a later layer wins regardless of specificity inside an earlier layer, which is a clean way to blend a framework with your own overrides. Support is broad in current browsers, though very old ones will ignore the layers entirely.
p { color: gray; }
.intro { color: blue; }
#lead { color: red; }
p { color: green; }
Watch out. Using important to win an argument. Fix the selector or the order instead.
Colours and units
Colours can be written as hex values, rgb or hsl functions, or named keywords. Modern CSS supports an optional alpha channel for transparency, so you can layer colours without creating separate image files. Choose colours with enough contrast for readable text.
Lengths come in absolute units like px and relative units like em, rem, and percentages. Rem is relative to the root font size and is excellent for typography; viewport units scale with the screen. Using relative units keeps your design flexible when users change their font settings.
body {
color: #222;
background: hsl(210 40% 96%);
font-size: 1rem;
line-height: 1.5;
}
Watch out. Setting body font-size in px, which ignores a user's browser font preference.
Flexbox
Flexbox lays items out along one axis. You set display to flex on a parent, then control direction, alignment, and spacing with properties on that parent. Children can grow, shrink, or keep their natural size, making flexbox ideal for toolbars, menus, and aligned rows.
The gap property adds space between items without margins on each child. align-items controls the cross axis and justify-content controls the main axis. Reaching for flexbox for one-dimensional layouts keeps your CSS short and removes many old float workarounds.
.toolbar {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
}
Watch out. Expecting flex-wrap to happen automatically. Set flex-wrap: wrap if items should move to new lines.
Grid
Grid handles two-dimensional layout: rows and columns at the same time. You define a grid with grid-template-columns and place items into cells or let the browser place them for you. This makes page-level layouts and card galleries straightforward.
The repeat function keeps column definitions tidy, and fr units divide available space proportionally. Named areas let you describe a layout in words, which reads almost like a picture of the page. Use grid for the overall skeleton and flexbox for the pieces inside it.
.gallery {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 16px;
}
Watch out. Using grid for a simple single row. Flexbox is usually clearer for one dimension.
Responsive design
Responsive design means the layout adapts to the viewport rather than assuming one width. Media queries apply a block of rules only when a condition matches, such as a maximum width. Combine them with flexible units and images that scale, and one stylesheet can serve phones and desktops.
Prefer a mobile-first approach: write the simple narrow layout first, then add rules for wider screens. This keeps the base stylesheet small and forces you to think about what matters most. Always test by actually resizing the browser, not by guessing.
@media (max-width: 600px) {
.gallery { grid-template-columns: 1fr; }
.toolbar { flex-direction: column; }
}
Watch out. Hiding content on small screens instead of reflowing it. Users still need that content.
CSS functions
CSS is not a programming language, but it does have functions. A function is a value that takes arguments and returns another value the browser can use. They let you calculate sizes, reuse tokens, clamp ranges, mix colours, and count elements without writing any JavaScript.
Functions compose: the result of one can be an argument to another. That is what makes them powerful. Browser support varies, so it helps to know which functions are ancient and safe and which arrived recently enough to need a fallback.
calc()
The calc function performs arithmetic inside a CSS value. It handles addition, subtraction, multiplication, and division, with the usual rule that you cannot add two different unit types. It is the classic way to combine percentages and pixels, and it works in all modern browsers.
.sidebar {
width: calc(100% - 240px);
margin-top: calc(2rem + 8px);
}
var() and custom properties
Custom properties are variables declared with a name starting with two dashes. You read them with var(), and they cascade like ordinary properties, which means a value set on a parent can be overridden on a child. This makes theme colours and spacing scales trivial to manage.
:root { --brand: #4a90e2; --gap: 1rem; }
.button {
background: var(--brand);
padding: var(--gap);
}
.button.dark { --brand: #1b3a6b; }
clamp(), min(), and max()
These functions pick values from a range. min takes the smallest argument, max takes the largest, and clamp takes a preferred value but keeps it between a floor and a ceiling. They are perfect for fluid typography and spacing that scales with the viewport without becoming unreadable.
h1 {
font-size: clamp(2rem, 5vw, 4rem);
}
.container { width: min(90%, 1200px); }
rgb() and hsl()
Colour functions build a colour from channels. rgb takes red, green, and blue; hsl takes hue, saturation, and lightness, which is often easier to adjust by hand. A slash and a percentage add transparency. Modern space-separated syntax is widely supported, while comma syntax is the safer fallback.
.overlay { background: rgb(0 0 0 / 50%); }
.accent { color: hsl(210 80% 45%); }
url() and attr()
The url function points to a resource, most often in background-image. The attr function reads an HTML attribute value, which is handy for generated content such as tooltips. Support for attr is broad in the content property but limited elsewhere, so treat it as a narrow tool.
.hero { background-image: url("hero.jpg"); }
.tag::after { content: " (" attr(data-count) ")"; }
counter()
CSS counters let you number elements automatically. You initialise and increment a counter with properties, then display it with counter() inside generated content. This is useful for numbered headings or lists where you want styling control beyond what ordered lists provide.
body { counter-reset: step; }
h2::before {
counter-increment: step;
content: counter(step) ". ";
}
Composing and support
Functions nest freely: clamp can contain calc, and rgb values can come from custom properties read with var(). That composability is where real power lives. Newer colour functions and relative colour syntax are still rolling out, so provide a plain fallback declaration before the advanced one.
.callout {
background: #4a90e2;
background: color-mix(in srgb, var(--brand) 80%, white);
}
Function reference
These are the functions you will reach for most often. Each one is shown with its syntax, its inputs and outputs, a working example, and the mistakes to avoid.
calc()
CSS function
calc() does basic arithmetic inside a CSS value. It lets you combine lengths, percentages, and numbers so sizes can adapt without hard-coded guesses.
| Syntax | calc(expression) |
|---|---|
| Parameters | expression — A calculation written in CSS, such as 100% - 2rem. |
| Returns | A computed value such as a length or number. |
.box {
width: calc(100% - 2rem);
margin: calc(1rem + 4px);
}
What you can do with it. Fill the width of a container minus fixed padding. Center an element with half its own width as an offset. Combine relative and absolute units in one value.
Choose it when. Choose calc() when a value must be computed from other values at render time, rather than calculating sizes yourself in JavaScript.
| Mistake | Fix |
|---|---|
| Omitting spaces around the plus and minus signs. | Write calc(100% - 2rem) with spaces on both sides of + and -. |
| Trying to multiply two lengths. | Multiply a length by a plain number, not by another length. |
var()
CSS function
var() inserts the value of a CSS custom property, also called a CSS variable. It lets you define a value once and reuse it across many rules.
| Syntax | var(--name, fallback) |
|---|---|
| Parameters | --name — The custom property to read. fallback — An optional value used when the property is not set. |
| Returns | The value stored in the custom property, or the fallback. |
:root {
--accent: #4a90e2;
}
.button {
background: var(--accent, #888);
color: white;
}
What you can do with it. Keep brand colours in one place. Build a theme that changes by redefining a few variables. Provide sensible defaults with a fallback value.
Choose it when. Choose var() for values you repeat or want to change globally, rather than editing every rule by hand.
| Mistake | Fix |
|---|---|
| Forgetting the two dashes when naming a custom property. | Start names with --, such as --accent. |
| Expecting variables in browsers that predate them. | They work in modern browsers; provide fallbacks where you still support old versions. |
clamp()
CSS function
clamp() keeps a value between a minimum and a maximum. It is ideal for fluid sizes that grow with the screen but never become too small or too large.
| Syntax | clamp(min, preferred, max) |
|---|---|
| Parameters | min — The lowest allowed value. preferred — The ideal, often flexible value. max — The highest allowed value. |
| Returns | A value between min and max, chosen from the preferred value. |
h1 {
font-size: clamp(1.5rem, 4vw, 3rem);
}
What you can do with it. Create responsive headings that scale smoothly. Keep a column width within readable limits. Set spacing that adapts but stays reasonable.
Choose it when. Choose clamp() when a property should scale with viewport size but stay inside bounds, rather than writing several media queries.
| Mistake | Fix |
|---|---|
| Putting the values in the wrong order. | Use min, preferred, max in that order. |
| Using clamp in a browser that predates it. | It is supported in modern browsers; give a plain fallback value first for older ones. |
min()
CSS function
min() picks the smallest value from a list of expressions. It is handy for capping a size at whichever constraint is tightest.
| Syntax | min(value1, value2, ...) |
|---|---|
| Parameters | values — Two or more comma-separated values to compare. |
| Returns | The smallest of the supplied values. |
.container {
width: min(90%, 800px);
}
What you can do with it. Let a layout use 90 percent of the screen but never exceed 800px. Cap a height at either a viewport fraction or a fixed limit. Combine with other math functions for responsive sizes.
Choose it when. Choose min() when you want the smaller of several limits, rather than hard-coding a breakpoint.
| Mistake | Fix |
|---|---|
| Thinking min() always picks a pixel value. | It compares computed values, so mixed units like % and px are fine. |
| Using it where older browser support is required. | It is widely supported now; add a fallback value for very old browsers. |
max()
CSS function
max() picks the largest value from a list of expressions. It works like the opposite of min() and is useful for setting a floor on a size.
| Syntax | max(value1, value2, ...) |
|---|---|
| Parameters | values — Two or more comma-separated values to compare. |
| Returns | The largest of the supplied values. |
.sidebar {
width: max(200px, 20%);
}
What you can do with it. Ensure a column is at least a readable width. Keep touch targets above a minimum size. Combine with min() for fully bounded responsive values.
Choose it when. Choose max() when a value must not fall below a threshold, rather than adding a special rule for small screens.
| Mistake | Fix |
|---|---|
| Confusing max() with the maximum allowed value. | max() returns the largest of its arguments; use min() to enforce an upper cap. |
| Expecting it in very old browsers. | It is supported in modern browsers; provide a fallback where needed. |
rgb()
CSS function
rgb() defines a colour by its red, green, and blue channels. Each channel is a number from 0 to 255, or a percentage, so you can build colours precisely.
| Syntax | rgb(red, green, blue) |
|---|---|
| Parameters | red — Red channel, 0 to 255 or a percentage. green — Green channel, 0 to 255 or a percentage. blue — Blue channel, 0 to 255 or a percentage. |
| Returns | A colour value that can be used anywhere a colour is accepted. |
.badge {
color: rgb(255, 255, 255);
background: rgb(30, 120, 200);
}
What you can do with it. Set exact brand colours. Mix with alpha via rgba() for translucent fills. Generate colours from numbers in a build script.
Choose it when. Choose rgb() when you want to specify a colour by numeric channels, rather than using a named colour or hex shorthand.
| Mistake | Fix |
|---|---|
| Using values above 255 without realising the browser clamps them. | Keep channels between 0 and 255 for predictable results. |
| Mixing percentage and number channels without meaning to. | Choose one style per colour for clarity. |
hsl()
CSS function
hsl() defines a colour by hue, saturation, and lightness. It is more intuitive than rgb() when you want to adjust a colour's brightness or make a palette.
| Syntax | hsl(hue, saturation, lightness) |
|---|---|
| Parameters | hue — An angle on the colour wheel, such as 210deg. saturation — A percentage of colour intensity. lightness — A percentage from dark to light. |
| Returns | A colour value usable anywhere a colour is accepted. |
.button {
background: hsl(210, 80%, 50%);
border-color: hsl(210, 80%, 35%);
}
What you can do with it. Build a palette by changing only lightness. Create hover states by tweaking one channel. Describe colours in a way that is easy to reason about.
Choose it when. Choose hsl() when you will adjust a colour's tone or brightness, rather than when you have a fixed hex value to paste in.
| Mistake | Fix |
|---|---|
| Forgetting the degree unit or percent signs. | Write hue with deg and saturation and lightness with %. |
| Assuming very old browsers support modern hsl syntax. | The classic comma form is widely supported; newer space-separated syntax is not in old browsers. |
url()
CSS function
url() points a CSS property at a file, most often an image. The path can be relative to the stylesheet and may be written with or without quotes.
| Syntax | url("image.png") |
|---|---|
| Parameters | path — The address of the resource, relative or absolute. |
| Returns | A reference to the external resource, not the resource data itself. |
.hero {
background-image: url("hero.jpg");
}
.icon {
background: url(icon.svg) no-repeat;
}
What you can do with it. Add a background image to an element. Load an icon or texture for a component. Reference a font file in an @font-face rule.
Choose it when. Choose url() when a CSS property needs an external file, rather than embedding data or generating an image in code.
| Mistake | Fix |
|---|---|
| A path that is wrong relative to the CSS file. | Check the path from the stylesheet's folder and confirm the file name. |
| Leaving spaces in an unquoted URL. | Quote the path when it contains spaces or special characters. |
attr()
CSS function
attr() reads the value of an HTML attribute on the element and uses it in CSS. It is most reliable for text content in pseudo-elements.
| Syntax | attr(data-label) |
|---|---|
| Parameters | attribute-name — The name of the attribute to read. type — An optional type and fallback; support is limited. |
| Returns | The attribute's value as a string in the supported cases. |
.tooltip::after {
content: " (" attr(data-label) ")";
}
<span class="tooltip" data-label="Save">Save</span>
What you can do with it. Show a tooltip from a data-label attribute. Display a value stored on the element without duplicating text. Add small labels driven by markup.
Choose it when. Choose attr() when a short text value already lives in an attribute, rather than generating extra markup just to show it. Browser support is limited outside the content property.
| Mistake | Fix |
|---|---|
| Using attr() for widths or colours and expecting it to work everywhere. | Beyond string content, support is limited; use custom properties for typed values. |
| Reading an attribute that is not on the element. | Ensure the attribute exists, or accept an empty result. |
counter()
CSS function
counter() inserts the current value of a CSS counter into generated content. It lets you number items automatically using CSS instead of typing numbers in HTML.
| Syntax | counter(name, style) |
|---|---|
| Parameters | name — The counter whose value you want to display. style — An optional list style such as upper-roman. |
| Returns | A string containing the counter's current value. |
body { counter-reset: section; }
h2::before {
counter-increment: section;
content: counter(section) ". ";
}
What you can do with it. Number headings in a document automatically. Create step lists without hard-coded numbers. Combine with counters() for nested numbering.
Choose it when. Choose counter() when numbering should update automatically as content changes, rather than maintaining numbers by hand in HTML.
| Mistake | Fix |
|---|---|
| Forgetting to initialise the counter with counter-reset. | Declare counter-reset on a parent before incrementing it. |
| Expecting the number to appear without generated content. | Place counter() inside the content property of ::before or ::after. |
env()
CSS function
env() reads environment values supplied by the browser, such as the safe area of a device with a notch. It helps content avoid being hidden by hardware features.
| Syntax | env(safe-area-inset-top, 0px) |
|---|---|
| Parameters | variable — The environment variable, such as safe-area-inset-left. fallback — A value used when the variable is unavailable. |
| Returns | The value of the environment variable, or the fallback. |
.header {
padding-top: env(safe-area-inset-top, 0px);
padding-left: env(safe-area-inset-left, 0px);
}
What you can do with it. Keep content clear of phone notches and rounded corners. Add safe padding only on devices that need it. Make full-screen layouts work on modern phones.
Choose it when. Choose env() when your layout reaches the screen edges on phones, rather than hard-coding padding that looks wrong everywhere else.
| Mistake | Fix |
|---|---|
| Expecting a visible effect on desktop. | Most desktop browsers report zero, so include a fallback and test on a real device. |
| Omitting viewport-fit=cover in the viewport meta tag. | Add viewport-fit=cover so safe-area values are reported. |
round()
CSS function
round() rounds a number to a multiple of another number using a chosen strategy. It is part of the newer CSS math functions that help with precise layout arithmetic.
| Syntax | round(strategy, value, step) |
|---|---|
| Parameters | strategy — One of nearest, up, or down. value — The number to round. step — The multiple to round to. |
| Returns | A number rounded to the nearest multiple of step. |
.grid {
width: round(nearest, 100%, 8px);
gap: round(up, 2vw, 4px);
}
What you can do with it. Snap a size to a grid of pixels. Round a computed spacing value to a tidy increment. Keep layouts aligned to a consistent rhythm.
Choose it when. Choose round() when a computed size must land on a fixed increment, rather than accepting fractional pixel values. Support is limited to recent browsers.
| Mistake | Fix |
|---|---|
| Using it in an older browser that does not support it. | round() is new; check support and provide a plain fallback value when needed. |
| Putting the arguments in the wrong order. | Write strategy first, then value, then step. |
minmax()
CSS function
minmax() defines a size range for a CSS Grid track. The track stays between the minimum and maximum you give, so the grid adapts to available space.
| Syntax | minmax(min, max) |
|---|---|
| Parameters | min — The smallest the track may be. max — The largest the track may be. |
| Returns | A track sizing value used in grid template definitions. |
.grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
}
What you can do with it. Build responsive card grids without media queries. Let columns share leftover space while keeping a minimum width. Prevent a track from collapsing too small.
Choose it when. Choose minmax() for flexible grid tracks that need a floor and a ceiling, rather than fixing every column width. It is well supported in modern browsers.
| Mistake | Fix |
|---|---|
| Using minmax() outside a grid track definition. | Use it in grid-template-columns or grid-template-rows. |
| Setting a min larger than a fixed max. | Keep the min at or below the max, or the min wins. |
counters()
CSS function
counters() combines the values of nested CSS counters into one string. It is the tool for numbering that includes parent levels, such as 2.3.1.
| Syntax | counters(name, separator) |
|---|---|
| Parameters | name — The counter to collect across all nesting levels. separator — The text placed between values, such as a dot. |
| Returns | A string joining all current values of the named counter. |
ol { counter-reset: item; }
li { counter-increment: item; }
li::before {
content: counters(item, ".") " ";
}
What you can do with it. Number nested lists like 1, 1.1, 1.2. Show section and subsection numbers together. Keep multi-level numbering in sync automatically.
Choose it when. Choose counters() when numbering has more than one level, rather than tracking the full number yourself. It is well supported in modern browsers.
| Mistake | Fix |
|---|---|
| Using counter() when you need nested levels. | Use counters() to join every level; counter() only shows the innermost value. |
| Forgetting the separator argument. | Pass a string such as a dot to separate the numbers. |
Common mistakes here
| Mistake | Fix |
|---|---|
| Writing calc(100% - 20) with a unitless number. | Give both operands compatible units, such as calc(100% - 20px). |
| Forgetting spaces around the minus in calc(). | Write calc(100% - 20px); spaces around operators are required. |
| Using var() for a property you never defined. | Declare the custom property, or supply a fallback like var(--x, 1rem). |
| Assuming attr() works for any property. | Use it mainly in content, and set real values with JavaScript elsewhere. |
| Using clamp with arguments in the wrong order. | Order is minimum, preferred, maximum. |
The example, line by line
This compact stylesheet shows custom properties, calculation, clamping, colour transparency, and flexbox working together.
| Code | What it does |
|---|---|
1:root { | Opens the root selector, the best place for global design tokens. |
2 --brand: #4a90e2; | Defines a brand colour as a custom property. |
3 --gap: 1rem; | Defines a reusable spacing value. |
4} | Closes the root rule. |
5.card { | Targets every element with the card class. |
6 width: calc(50% - var(--gap)); | Uses calc and var together to size the card minus one gap. |
7 padding: clamp(8px, 2vw, 24px); | Clamps padding between 8 and 24 pixels based on viewport width. |
8 background: rgb(74 144 226 / 10%); | Sets a translucent blue background with the modern rgb syntax. |
9 display: flex; | Makes the card a flex container for its children. |
10 gap: var(--gap); | Spaces those children using the shared gap token. |
11} | Closes the card rule. |
12.card h2 { color: var(--brand); } | Colours card headings by reading the brand custom property. |
:root {
--brand: #4a90e2;
--gap: 1rem;
}
.card {
width: calc(50% - var(--gap));
padding: clamp(8px, 2vw, 24px);
background: rgb(74 144 226 / 10%);
display: flex;
gap: var(--gap);
}
.card h2 { color: var(--brand); }
Worked variations
A fluid type scale
Clamp is ideal for type that must stay readable on both a phone and a large monitor. The middle value uses a viewport unit so it grows smoothly, while the outer values stop it from becoming too small or absurdly large.
:root {
--step-0: clamp(1rem, 0.9rem + 0.5vw, 1.25rem);
--step-1: clamp(1.25rem, 1rem + 1.2vw, 2rem);
}
p { font-size: var(--step-0); }
h1 { font-size: var(--step-1); }
A themed component
Because custom properties cascade, changing one on a subtree retheme everything inside it. This is a clean alternative to duplicating a whole rule set for a dark variant.
.panel { background: var(--surface, white); color: var(--ink, black); }
.panel.night {
--surface: #222;
--ink: #eee;
}
Common mistakes
| Mistake | Fix |
|---|---|
| Writing CSS from screenshots without reusable tokens. | Define colours and spacing as custom properties first. |
| Using floats for page layout. | Use flexbox or grid instead. |
| Setting fixed pixel widths everywhere. | Use relative units and min or max to stay flexible. |
| Fighting specificity with more specific selectors. | Keep selectors flat and let source order do the work. |
| Testing only at one window size. | Resize the browser and check narrow and wide breakpoints. |
Practice
- Create a custom property for your brand colour and apply it to three elements.
- Build a two-column layout with flexbox and a gap of your choice.
- Write a clamp expression for a heading that stays between 1.5rem and 3rem.
- Recreate a three-column card gallery with grid and a media query for one column.