CSS Tutorial: Complete Guide to Layout, Flexbox, Grid and Responsive Design

Web Development 27 min readUpdated Oct 30, 2026
5 views0 comments

CSS (Cascading Style Sheets) is the language that makes the web look good. HTML says what is on the page: a heading, a list, a form. CSS says how it looks and where it sits: colours, fonts, spacing, layout, animation, and how everything adapts from a phone to a wide monitor. It is easy to start (you can change a page’s colour in one line) and takes real understanding to master, mostly because of four ideas: the cascade, the box model, flexbox and grid. This tutorial explains those clearly, then shows responsive design and modern CSS, and finishes with a complete responsive landing page.

It is the second tutorial of a series with HTML and JavaScript. Every CSS declaration in the examples was checked by a real browser engine, and the layout demos were rendered and measured to confirm that the results described in the text are the real results.

Contents

1. How CSS works

A CSS rule has a selector (which elements?) and a declaration block (what to do to them?). Each declaration is a property and a value, ending with a semicolon:

h1 {
  color: #1e293b;          /* property: value; */
  font-size: 2.5rem;
  margin-bottom: 1rem;
}

p, li {                    /* a comma lets several selectors share one rule */
  line-height: 1.6;
}

There are three ways to add CSS to a page. The best, by far, is an external file, because the browser caches it and one file styles the whole site:

<link rel="stylesheet" href="style.css">             <!-- 1. external file, in the head: the standard way -->

<style>                                             /* 2. internal: handy for small tests */
  body { margin: 0; }
</style>

<p style="color: red;">Inline.</p>                  <!-- 3. inline: hard to maintain and hard to override: avoid -->

Comments in CSS are written /* like this */. Open your browser’s developer tools (F12) and use the Elements panel: click any element and the Styles tab shows every rule that applies to it, which ones win, and lets you edit values live. This is the fastest way to learn and to fix problems.

2. Selectors

Selector Selects Example
p All elements of that type p { ... }
.card Elements with class="card" (reusable) .card { ... }
#header The one element with id="header" #header { ... }
* Everything * { box-sizing: border-box; }
nav a Descendant: any a inside nav
ul > li Child: only direct children
h2 + p Adjacent sibling: the paragraph right after an h2
h2 ~ p General sibling: all following paragraphs
a[href^="https"] Attribute selectors: [x], [x="v"], ^= starts, $= ends, *= contains
.card.featured Both classes on the same element
a:hover { text-decoration: underline; }               /* pseudo-classes: states and positions */
a:focus-visible { outline: 3px solid #4f46e5; outline-offset: 2px; }   /* keyboard focus: never remove it without a replacement! */
input:invalid { border-color: crimson; }
input:checked + label { font-weight: 700; }
li:first-child { font-weight: 700; }
li:nth-child(odd) { background: #f1f5f9; }              /* 1st, 3rd, 5th... */
li:nth-child(3n + 1) { color: #4f46e5; }                 /* every third, starting from the first */
li:not(.done) { opacity: 1; }
:is(h1, h2, h3):hover { color: #4f46e5; }                /* a shorter way to write a group */
.card:has(img) { padding-top: 0; }                       /* "a card that contains an image": the long-awaited parent selector */

p::first-line { font-variant: small-caps; }              /* pseudo-elements: parts of an element */
blockquote::before { content: "“"; font-size: 2em; }     /* generated content */
input::placeholder { color: #94a3b8; }
li::marker { color: #4f46e5; }
::selection { background: #fde68a; }

Pseudo-classes use one colon (:hover) and describe a state; pseudo-elements use two (::before) and describe a part of the element. Style links in this order if you set several states: link, visited, focus, hover, active (the “LVFHA” rule), because later rules win ties.

3. The cascade, specificity and inheritance

When two rules set the same property on the same element, which wins? This is the “cascading” in Cascading Style Sheets, and it follows three rules, in this order:

  1. Importance and origin. A declaration marked !important beats normal ones. Avoid it: it makes later changes painful.
  2. Specificity. The more specific selector wins. Count it like a score with three digits: ids (hundreds), then classes, attributes and pseudo-classes (tens), then element types (ones). Inline styles beat all of them.
  3. Order. If the specificity is equal, the rule that comes last wins.
Selector Score (ids, classes, types)
p 0, 0, 1
.note 0, 1, 0
p.note 0, 1, 1
nav ul li a:hover 0, 1, 4
#title 1, 0, 0 (beats any number of classes)
<!DOCTYPE html>
<html lang="en">
<head>
<style>
  p { color: red; }            /* 0,0,1 */
  .note { color: green; }      /* 0,1,0 */
  p.note { color: orange; }    /* 0,1,1 */
  #t { color: blue; }          /* 1,0,0: this wins, though it comes... */
  p.note { color: orange; }    /* ...before this identical-score rule, which cannot beat an id */
</style>
</head>
<body>
  <p id="t" class="note">Which colour am I? Blue: the id rule is the most specific.</p>
</body>
</html>

Inheritance. Some properties pass from parent to children automatically: text-related ones such as color, font-family, font-size, line-height, text-align. Box-related ones (margin, padding, border, background) do not. So you set the font once on body and everything inherits it. Force the behaviour with the keywords inherit, initial (the CSS default) and unset.

How to stay out of trouble: use classes for almost everything, keep selectors short (one or two parts), do not use ids for styling, and never fight specificity with !important. If you need to organise a large stylesheet, cascade layers (@layer reset, base, components, utilities;) let you decide the priority of whole groups of rules regardless of specificity.

4. Units, colours and calculations

Unit Meaning Use it for
px A CSS pixel (fixed) Borders, shadows, small details
rem The root font size (16px by default) Font sizes and spacing: it respects the visitor’s browser setting
em The element’s own font size Spacing that should scale with the text (buttons)
% Relative to the parent Widths
vw, vh, dvh 1% of the viewport width or height (dvh accounts for mobile address bars) Full-screen sections, fluid type
ch The width of the character “0” Comfortable line length: max-width: 65ch
fr A fraction of free space (grid only) Grid columns

Do not set font sizes in px for body text: people with low vision raise the default size in the browser, and px ignores it. Use rem.

.colours {
  color: tomato;                       /* a named colour */
  color: #4f46e5;                      /* hex: red, green, blue */
  color: #4f46e5cc;                    /* with alpha (transparency) */
  color: rgb(79 70 229);               /* modern syntax: spaces, no commas */
  color: rgb(79 70 229 / 80%);
  color: hsl(243 75% 59%);             /* hue (0-360), saturation, lightness: easiest to adjust by hand */
  color: hsl(243 75% 59% / 0.5);
  background: oklch(62% 0.2 275);      /* a newer, perceptually even colour space */
}

.maths {
  width: calc(100% - 2rem);            /* mix units: the browser calculates */
  font-size: clamp(1rem, 0.9rem + 1.5vw, 1.75rem);   /* never smaller than 1rem, never bigger than 1.75rem, fluid in between */
  padding: max(1rem, 3vw);
  width: min(100%, 60rem);             /* "as wide as the screen, but not more than 60rem" */
}

Convert between colour formats and generate shades with our free colour converter, and always check that text and background have enough contrast (at least 4.5:1 for normal text) with the contrast checker.

5. Text and fonts

body {
  font-family: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;   /* a stack: the browser uses the first available font */
  font-size: 1rem;
  line-height: 1.6;                  /* unitless: 1.6 times the font size. Body text reads best between 1.4 and 1.7 */
  color: #1e293b;
}

h1, h2, h3 {
  line-height: 1.2;
  font-weight: 700;
  letter-spacing: -0.02em;
  text-wrap: balance;                /* even line lengths in headings */
}

.article p { max-width: 65ch; }      /* about 65 characters per line is the most readable */
.lead { font-size: 1.25rem; color: #475569; }
.centered { text-align: center; }
.caps { text-transform: uppercase; letter-spacing: 0.08em; font-size: 0.8rem; }
a { color: #4f46e5; text-decoration-thickness: 2px; text-underline-offset: 3px; }
.truncate { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }   /* one line, ending with ... */
.clamp-3 { display: -webkit-box; -webkit-line-clamp: 3; -webkit-box-orient: vertical; overflow: hidden; }
.long-word { overflow-wrap: anywhere; }   /* lets very long words or URLs break instead of overflowing */

@font-face {                          /* load your own font file */
  font-family: "Inter";
  src: url("fonts/inter.woff2") format("woff2");
  font-weight: 100 900;               /* a variable font: every weight in one file */
  font-display: swap;                 /* show text immediately in a fallback font, then swap */
}

Fonts matter for speed: use WOFF2 files, load only the weights you need, host them yourself (it is faster and more private than third-party fonts), and set font-display: swap. A system font stack costs nothing.

6. The box model

Every element is a rectangular box made of four layers, from the inside out: content, padding (space inside the border), border, and margin (space outside, between elements). Understanding this explains most layout surprises.

.card {
  width: 300px;
  padding: 1rem 1.5rem;                  /* vertical, horizontal. Four values go top, right, bottom, left (clockwise) */
  border: 2px solid #cbd5e1;
  border-radius: 12px;
  margin: 1rem auto;                     /* auto on the sides centres a box that has a width */
}

By default (box-sizing: content-box), width sets the width of the content only, and padding and border are added on top. A box with width: 200px; padding: 20px; border: 5px is really 250px wide, which breaks layouts. Almost every modern stylesheet starts with:

*, *::before, *::after { box-sizing: border-box; }     /* width now includes padding and border: what you expect */
<!DOCTYPE html>
<html lang="en">
<head>
<style>
  div { width: 200px; padding: 20px; border: 5px solid #4f46e5; margin: 10px 0; }
  .b { box-sizing: border-box; }
</style>
</head>
<body>
  <div id="a">content-box (the default): 250px wide in total</div>
  <div id="b" class="b">border-box: exactly 200px wide in total</div>
</body>
</html>

Margin collapsing. Vertical margins between neighbouring blocks do not add up: the larger one wins. Two paragraphs with margin-bottom: 20px and margin-top: 30px are 30px apart, not 50px. (Margins of flex and grid items do not collapse.) Many developers avoid the issue by using only margin-bottom, or gap.

<!DOCTYPE html>
<html lang="en">
<head>
<style>
  body { margin: 0; }
  #first { margin: 0 0 20px; }
  #second { margin: 30px 0 0; }
</style>
</head>
<body>
  <p id="first">First paragraph (margin-bottom 20px)</p>
  <p id="second">Second paragraph (margin-top 30px)</p>
</body>
</html>

Other box properties: overflow: auto adds scrollbars when content does not fit (hidden cuts it off); min-width, max-width, min-height set limits (max-width: 100% is the key to responsive images); outline draws a line outside the border without taking up space (used for focus). Use aspect-ratio: 16 / 9 to keep a box’s shape.

7. Display and positioning

The display property decides how a box behaves. block elements (div, p, section) start on a new line and fill the available width. inline elements (span, a, strong) sit within a line of text, and ignore width, height and vertical margins. inline-block sits in a line but accepts width and height. display: none removes an element completely (visibility: hidden hides it but keeps its space). flex and grid are the layout modes, covered next.

.badge { display: inline-block; padding: 0.2em 0.6em; border-radius: 999px; background: #e0e7ff; }

.parent { position: relative; }                       /* the reference for absolutely positioned children */
.close-button { position: absolute; top: 0.5rem; right: 0.5rem; }    /* placed relative to .parent */
.header { position: sticky; top: 0; background: #fff; z-index: 10; }  /* scrolls normally, then sticks to the top */
.cookie-banner { position: fixed; bottom: 0; left: 0; right: 0; }     /* fixed to the screen */
.cover { position: absolute; inset: 0; }                              /* inset: 0 = top, right, bottom, left all 0 */
position Behaviour
static The default: normal flow
relative Normal flow, but can be nudged with top/left; it becomes the reference for absolute children
absolute Removed from the flow and placed relative to the nearest positioned ancestor
fixed Fixed relative to the screen
sticky Normal flow until it would scroll out of view, then sticks
<!DOCTYPE html>
<html lang="en">
<head>
<style>
  body { margin: 0; }
  #box { position: relative; width: 300px; height: 120px; margin: 40px; background: #e2e8f0; }
  #pin { position: absolute; top: 10px; right: 20px; width: 40px; height: 40px; background: #4f46e5; }
</style>
</head>
<body>
  <div id="box"><div id="pin"></div></div>
</body>
</html>

z-index controls which positioned elements are on top, but only within the same stacking context; if a high z-index “does not work”, look for a parent that creates its own context (a transform, opacity below 1, or position with a z-index). Keep a small scale of values (1, 10, 100) instead of 99999.

8. Flexbox

Flexbox lays items out in a row or a column and distributes the space between them. It is the right tool for navigation bars, button groups, toolbars, a row of cards, and centring things. You declare display: flex on the container; its direct children become flex items.

.row {
  display: flex;
  flex-direction: row;               /* row (default) | column | row-reverse | column-reverse: the MAIN axis */
  justify-content: space-between;    /* distribute along the main axis: flex-start | center | flex-end | space-between | space-around | space-evenly */
  align-items: center;               /* align on the CROSS axis: stretch (default) | flex-start | center | flex-end | baseline */
  gap: 1rem;                         /* space between items: use this instead of margins */
  flex-wrap: wrap;                   /* allow items to move to a new line when there is no room */
}

.item { flex: 0 1 auto; }            /* flex: grow shrink basis (this is the default) */
.grow { flex: 1; }                   /* take an equal share of the free space */
.fixed { flex: 0 0 200px; }          /* never grow or shrink: exactly 200px */
.push-right { margin-left: auto; }   /* an auto margin absorbs all the free space: pushes the item to the end */
.first { order: -1; }                /* change the visual order (keep source order meaningful for accessibility) */
.self { align-self: flex-end; }      /* one item aligns differently */

The mental model: justify-content works along the main axis (the direction of the row or column) and align-items along the cross axis. Switch to flex-direction: column and they swap roles. The three numbers of flex are: grow (how much extra space to take), shrink (how much to give up when space is short) and basis (the starting size).

The classic patterns

/* 1. Centre anything, both ways */
.center { display: flex; justify-content: center; align-items: center; min-height: 100vh; }

/* 2. A navigation bar: logo on the left, links on the right */
.nav { display: flex; align-items: center; gap: 1rem; }
.nav .logo { margin-right: auto; }

/* 3. Sticky footer: the footer sits at the bottom even on short pages */
body { display: flex; flex-direction: column; min-height: 100vh; margin: 0; }
main { flex: 1; }

/* 4. A form row: the input takes all the space, the button its own size */
.search { display: flex; gap: 0.5rem; }
.search input { flex: 1; }
<!DOCTYPE html>
<html lang="en">
<head>
<style>
  body { margin: 0; }
  #parent { display: flex; justify-content: center; align-items: center; width: 400px; height: 200px; background: #e2e8f0; }
  #child { width: 100px; height: 50px; background: #4f46e5; }
</style>
</head>
<body>
  <div id="parent"><div id="child"></div></div>
</body>
</html>

9. Grid

Grid lays items out in rows and columns at the same time: a two-dimensional layout. Use it for whole-page layouts, card galleries, dashboards, and any design with aligned rows and columns. (Rule of thumb: flexbox for one direction, grid for two. They work well together: grid for the page, flexbox inside the components.)

.grid {
  display: grid;
  grid-template-columns: 200px 1fr 1fr;      /* three columns: fixed, then two that share the rest equally */
  grid-template-columns: repeat(3, 1fr);     /* three equal columns */
  gap: 1.5rem;                               /* row and column gaps */
}

.wide { grid-column: span 2; }               /* this item takes two columns */
.tall { grid-row: span 2; }
.start { grid-column: 1 / 3; }               /* from column line 1 to line 3 */

/* The most useful line of CSS for responsive layouts: as many columns as fit, no media queries needed */
.cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 1rem;
}

/* Named areas make page layouts readable */
.page {
  display: grid;
  grid-template-columns: 220px 1fr;
  grid-template-areas:
    "header header"
    "sidebar main"
    "footer footer";
  min-height: 100vh;
}
.page > header { grid-area: header; }
.page > aside  { grid-area: sidebar; }
.page > main   { grid-area: main; }
.page > footer { grid-area: footer; }

.center-grid { display: grid; place-items: center; }     /* the shortest way to centre something */

The fr unit divides the free space into shares: 1fr 2fr gives the second column twice the width of the first. minmax(250px, 1fr) means “at least 250px, growing to share the space”. With repeat(auto-fit, ...) the browser puts in as many columns as fit: three on a wide screen, two on a tablet, one on a phone, with no breakpoints. Let us measure it:

<!DOCTYPE html>
<html lang="en">
<head>
<style>
  body { margin: 0; }
  .cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 16px; }
  .cards div { background: #e0e7ff; height: 60px; }
</style>
</head>
<body>
  <div class="cards"><div></div><div></div><div></div><div></div><div></div></div>
</body>
</html>

On a 900px wide screen that gives three columns; on 500px, one column. Flexbox or grid?

You want… Use
A row of buttons or a toolbar, items sized by their content Flexbox
Centre one thing Either: display: grid; place-items: center is the shortest
A card gallery that adapts to the width Grid with auto-fit and minmax
A page with header, sidebar, main and footer Grid with areas
Items that wrap and keep their own width Flexbox with flex-wrap
Rows and columns that must line up Grid

10. Responsive design

More than half of web visits come from phones. A responsive site adapts to every screen size from a single set of files. The recipe has four ingredients:

  1. The viewport meta tag in the HTML head: <meta name="viewport" content="width=device-width, initial-scale=1">. Without it phones pretend to be 980px wide and shrink the page.
  2. Fluid layouts: percentages, fr, flexbox and grid instead of fixed pixel widths.
  3. Flexible media: img, video { max-width: 100%; height: auto; }.
  4. Media queries for the places where the design must change.

Work mobile first: write the simple single-column phone layout as the base, then add rules for larger screens with min-width. Phones load less CSS, and the thinking is simpler.

img, video { max-width: 100%; height: auto; }

.layout { display: grid; gap: 1rem; }                  /* phone: one column */

@media (min-width: 640px) {                              /* tablet and up */
  .layout { grid-template-columns: 1fr 1fr; }
}

@media (min-width: 1024px) {                             /* desktop */
  .layout { grid-template-columns: 2fr 1fr; }
  .container { max-width: 70rem; margin-inline: auto; }
}

/* Respect the visitor's settings */
@media (prefers-reduced-motion: reduce) {
  * { animation: none !important; transition: none !important; }
}
@media (prefers-color-scheme: dark) {
  body { background: #0f172a; color: #e2e8f0; }
}
@media print {
  nav, footer, .ads { display: none; }                   /* cut the menus when printing or saving as PDF */
}
@media (hover: hover) {
  .card:hover { transform: translateY(-4px); }           /* hover effects only on devices that can hover */
}

Choose breakpoints where your design breaks, not by device names: shrink the browser until something looks bad, and add a breakpoint there. Common starting points are about 640px, 768px, 1024px and 1280px. Fluid typography with clamp() removes many queries: font-size: clamp(1.75rem, 1rem + 3vw, 3rem). Use logical properties (margin-inline, padding-block, inset-inline-start) so that layouts also work for right-to-left languages such as Arabic.

Container queries

A media query looks at the screen. A container query looks at the size of the component’s parent, so a card can adapt wherever you put it (in a wide main column or a narrow sidebar):

.card-wrapper { container-type: inline-size; container-name: card; }

.card { display: grid; gap: 0.75rem; }
@container card (min-width: 28rem) {
  .card { grid-template-columns: 8rem 1fr; }          /* image beside the text when the wrapper is wide enough */
}

To test your work, use the device toolbar in the browser’s developer tools (Ctrl+Shift+M), then check on a real phone. Measure your page’s speed and weight with our page speed checker: large images are the usual culprit.

<!DOCTYPE html>
<html lang="en">
<head>
<style>
  body { margin: 0; font-size: 1rem; }
  h1 { margin: 0; font-size: clamp(1rem, 2vw + .5rem, 2rem); }       /* 2vw + 8px, held between 16px and 32px */
</style>
</head>
<body>
  <h1 id="fluid">A fluid heading</h1>
</body>
</html>

11. Backgrounds, gradients, shadows and images

.hero {
  background-color: #1e293b;
  background-image: linear-gradient(135deg, #4f46e5 0%, #06b6d4 100%);   /* gradients are images */
  background-image: radial-gradient(circle at top right, #f472b6, transparent 60%), url("hero.jpg");   /* layers: the first is on top */
  background-size: cover;                /* fill the box, cropping if needed (contain: fit inside) */
  background-position: center;
  background-repeat: no-repeat;
  color: #fff;
}

.card {
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 10px 30px rgb(15 23 42 / 0.15), 0 2px 6px rgb(15 23 42 / 0.1);   /* x, y, blur, then colour; stack several */
}
.glow { box-shadow: 0 0 0 4px rgb(79 70 229 / 0.3); }          /* a ring: 0 blur, 4px spread */
.glass { background: rgb(255 255 255 / 0.6); backdrop-filter: blur(10px); }
.text-gradient { background: linear-gradient(90deg, #4f46e5, #ec4899); -webkit-background-clip: text; background-clip: text; color: transparent; }

img.cover { width: 100%; height: 240px; object-fit: cover; }   /* crop an image to fill its box without squashing it */
img.avatar { width: 64px; aspect-ratio: 1; border-radius: 50%; object-fit: cover; }
.dim { opacity: 0.6; filter: grayscale(1) blur(1px); }

Design gradients and shadows visually, then copy the CSS: our free CSS gradient generator and box-shadow generator let you adjust the values and see the result live. Resize and compress your pictures first with the image resizer and compressor.

12. Transitions and animations

A transition animates a change between two states (usually on hover or focus). An animation runs a sequence of steps defined with @keyframes, by itself or in a loop.

.button {
  background: #4f46e5;
  color: #fff;
  padding: 0.7rem 1.2rem;
  border-radius: 0.5rem;
  transition: background-color 0.2s ease, transform 0.2s ease;       /* property, duration, easing */
}
.button:hover, .button:focus-visible { background: #4338ca; transform: translateY(-2px); }
.button:active { transform: translateY(0) scale(0.98); }

.rotate { transform: rotate(45deg); }
.zoom { transform: scale(1.1); }
.slide { transform: translateX(100%); }

@keyframes fade-in {
  from { opacity: 0; transform: translateY(12px); }
  to   { opacity: 1; transform: translateY(0); }
}
.appear { animation: fade-in 0.6s ease-out both; }

@keyframes spin { to { transform: rotate(360deg); } }
.spinner { width: 2rem; height: 2rem; border: 3px solid #cbd5e1; border-top-color: #4f46e5; border-radius: 50%; animation: spin 0.8s linear infinite; }

Animate only transform and opacity. Those are handled by the graphics card and stay smooth; animating width, top or margin forces the browser to recalculate the layout on every frame. Keep animations short (150 to 400 milliseconds for interface feedback), and honour prefers-reduced-motion (shown earlier) because motion can make some people ill.

13. Custom properties, themes and dark mode

Custom properties (CSS variables) store a value once and reuse it everywhere. They start with two dashes, are read with var(), and, unlike variables in Sass, they are live in the browser, so they can change by context and with JavaScript.

:root {                                   /* :root is the html element: the top of the cascade */
  --brand: #4f46e5;
  --brand-dark: #4338ca;
  --text: #1e293b;
  --bg: #ffffff;
  --radius: 0.75rem;
  --space: 1rem;
  color-scheme: light dark;               /* lets the browser style form controls and scrollbars for both themes */
}

@media (prefers-color-scheme: dark) {
  :root { --text: #e2e8f0; --bg: #0f172a; }      /* redefine the variables: the whole site switches theme */
}
:root[data-theme="dark"] { --text: #e2e8f0; --bg: #0f172a; }      /* or switch with a button that sets data-theme */

body { background: var(--bg); color: var(--text); }
.button { background: var(--brand); border-radius: var(--radius); padding: var(--space); }
.button:hover { background: var(--brand-dark); }
.compact { --space: 0.5rem; }                     /* override for one component and its children */
.box { width: calc(var(--space) * 20); color: var(--missing, #64748b); }   /* a fallback after the comma */
<!DOCTYPE html>
<html lang="en">
<head>
<style>
  :root { --bg: #ffffff; --text: #1e293b; }
  body { background: var(--bg); color: var(--text); }
  .dark { --bg: #0f172a; --text: #e2e8f0; }
</style>
</head>
<body>
  <p id="plain">Light theme by default</p>
  <div id="themed" class="dark"><p id="inner" style="background: var(--bg); color: var(--text)">Dark inside this block</p></div>
</body>
</html>

One small JavaScript snippet toggles the theme and remembers the choice (see the JavaScript tutorial): document.documentElement.dataset.theme = "dark"; localStorage.theme = "dark";. Keep the default colours accessible in both themes: contrast needs to be checked twice.

14. Modern CSS you should know

CSS has gained more in the last few years than in the ten before. These features work in all current browsers:

/* Nesting: write the rules for a component inside it, like Sass */
.card {
  padding: 1rem;
  border-radius: 12px;
  & h3 { margin-top: 0; }
  &:hover { box-shadow: 0 8px 24px rgb(0 0 0 / 0.12); }
  @media (min-width: 640px) { padding: 1.5rem; }
}

/* :has() - style a parent from its content */
.form-row:has(input:invalid) { border-left: 4px solid crimson; }
label:has(input:checked) { background: #e0e7ff; }

/* Cascade layers - control priority without specificity wars */
@layer reset, base, components, utilities;
@layer components { .btn { padding: 0.5rem 1rem; } }
@layer utilities { .hidden { display: none; } }

/* Feature queries */
@supports (display: grid) and (gap: 1rem) { .gallery { display: grid; gap: 1rem; } }

html { scroll-behavior: smooth; }
:target { scroll-margin-top: 5rem; }                    /* anchors do not hide under a sticky header */
input[type="checkbox"], input[type="radio"] { accent-color: #4f46e5; }
.box { aspect-ratio: 16 / 9; inset: 0; margin-inline: auto; padding-block: 1rem; }
.tooltip { position: absolute; inset-inline-start: 0; }
.balanced { text-wrap: balance; }
.sticky-top { position: sticky; top: 0; }
.no-scroll-jump { overscroll-behavior: contain; }
.fill { min-height: 100dvh; }                           /* dvh: the real visible height on mobile browsers */

:has(), nesting, container queries, @layer and the colour functions (oklch, color-mix()) change how you structure stylesheets: look them up on MDN and try each in a small page. Always check support at caniuse.com, and use @supports when you need a fallback.

15. Organising CSS and fixing problems

  • Start every project with a small reset: *, *::before, *::after { box-sizing: border-box; }, body { margin: 0; } and img { max-width: 100%; display: block; }.
  • Name classes by what things are, not how they look: .card, .nav-link, .price, not .red-box. The BEM convention is popular (.card, .card__title, .card--featured) because it keeps selectors flat and predictable.
  • Prefer classes and low specificity, and avoid !important and ids.
  • Use custom properties for colours, spacing and radius, so a redesign changes one place.
  • Group the stylesheet: variables, reset, base elements, layout, components, utilities, media queries next to the thing they change.
  • Remove what you do not use, and minify for production (build tools do this).
  • For big projects, consider a framework: Tailwind CSS (utility classes written in your HTML), Bootstrap (ready-made components), or a component framework’s scoped CSS. Learn plain CSS first, because they all produce plain CSS.

Debugging checklist

  1. Right-click the element, choose Inspect, and read the Styles pane. A struck-through declaration lost to a more specific rule; a declaration with a yellow warning icon is invalid (typo in the property or value).
  2. Look at the Computed tab to see the final value and which rule it came from.
  3. Look at the box diagram: where did the extra space come from, padding or margin?
  4. Temporarily add outline: 1px solid red; to elements to see their real boxes.
  5. Is the CSS file really loaded? (Network panel; a wrong path or a cached old copy: hard refresh with Ctrl+Shift+R.)

Mistakes everybody makes once

  • Forgetting box-sizing: border-box and wondering why 100% width plus padding overflows.
  • Horizontal scrollbars on phones. Usual causes: a fixed pixel width, width: 100vw (it includes the scrollbar; use 100%), a wide table or image without max-width: 100%, or a long unbreakable word.
  • Setting height instead of letting content decide. Use min-height so text can grow.
  • Centring confusion: text-align: center centres text inside a box, margin-inline: auto centres a box that has a width, flexbox or grid centre children.
  • Removing the focus outline (outline: none) with nothing in its place. Keyboard users cannot see where they are.
  • Using px for font sizes, and low-contrast grey text.
  • z-index wars and !important piled on !important.
  • Making a clickable div instead of a real a or button and styling it to look right: the HTML should be correct first.

16. Project: a responsive landing page

This page puts everything together: reset, custom properties with dark mode, a flexbox header, a hero with a gradient and fluid type, a grid of cards that adapts without breakpoints, hover and focus states, and a footer. Paste it into a file, open it, then resize the window and try the dark mode (in the browser’s developer tools, Rendering panel, “emulate prefers-color-scheme”).

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Northwind Studio</title>
  <style>
    /* 1. Reset and variables */
    *, *::before, *::after { box-sizing: border-box; }
    :root {
      --brand: #4f46e5; --brand-dark: #4338ca;
      --text: #1e293b; --muted: #475569; --bg: #ffffff; --surface: #f1f5f9; --line: #e2e8f0;
      --radius: 1rem; --space: clamp(1rem, 3vw, 2rem);
      color-scheme: light dark;
    }
    @media (prefers-color-scheme: dark) {
      :root { --text: #e2e8f0; --muted: #94a3b8; --bg: #0f172a; --surface: #1e293b; --line: #334155; --brand: #818cf8; --brand-dark: #a5b4fc; }
    }
    body { margin: 0; font-family: system-ui, -apple-system, "Segoe UI", sans-serif; line-height: 1.6; color: var(--text); background: var(--bg); }
    img { max-width: 100%; display: block; }
    a { color: var(--brand); }
    :focus-visible { outline: 3px solid var(--brand); outline-offset: 3px; }

    /* 2. Layout helpers */
    .container { width: min(100% - 2 * var(--space), 70rem); margin-inline: auto; }

    /* 3. Header: flexbox */
    header { border-bottom: 1px solid var(--line); }
    .bar { display: flex; flex-wrap: wrap; align-items: center; gap: 1rem; padding-block: 1rem; }
    .logo { margin-right: auto; font-weight: 800; font-size: 1.25rem; text-decoration: none; color: var(--text); }
    nav ul { display: flex; flex-wrap: wrap; gap: 1.25rem; list-style: none; margin: 0; padding: 0; }
    nav a { text-decoration: none; color: var(--muted); }
    nav a:hover { color: var(--brand); }

    /* 4. Buttons */
    .button { display: inline-block; padding: 0.75rem 1.25rem; border-radius: 0.6rem; background: var(--brand); color: #0f172a;
              font-weight: 700; text-decoration: none; transition: transform 0.2s ease, background-color 0.2s ease; }
    @media (prefers-color-scheme: light) { .button { color: #fff; } }
    .button:hover { background: var(--brand-dark); transform: translateY(-2px); }

    /* 5. Hero */
    .hero { padding-block: clamp(3rem, 10vw, 7rem); background: linear-gradient(135deg, rgb(79 70 229 / 0.18), rgb(6 182 212 / 0.18)); }
    .hero h1 { font-size: clamp(2rem, 1rem + 4vw, 3.75rem); line-height: 1.1; letter-spacing: -0.02em; margin: 0 0 1rem; text-wrap: balance; }
    .hero p { font-size: 1.2rem; color: var(--muted); max-width: 40rem; margin: 0 0 1.5rem; }

    /* 6. Cards: grid with auto-fit, no media query needed */
    .section { padding-block: clamp(2.5rem, 6vw, 4.5rem); }
    .cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(16rem, 1fr)); gap: var(--space); }
    .card { background: var(--surface); border: 1px solid var(--line); border-radius: var(--radius); padding: 1.5rem; transition: transform 0.2s ease, box-shadow 0.2s ease; }
    .card:hover { transform: translateY(-4px); box-shadow: 0 12px 30px rgb(15 23 42 / 0.15); }
    .card h3 { margin-top: 0; }
    .card p { color: var(--muted); margin-bottom: 0; }

    /* 7. Footer */
    footer { border-top: 1px solid var(--line); padding-block: 2rem; color: var(--muted); }
    @media (prefers-reduced-motion: reduce) { * { transition: none !important; } }
  </style>
</head>
<body>
  <header>
    <div class="container bar">
      <a class="logo" href="#">Northwind</a>
      <nav aria-label="Main">
        <ul>
          <li><a href="#services">Services</a></li>
          <li><a href="#work">Work</a></li>
          <li><a href="#contact">Contact</a></li>
        </ul>
      </nav>
    </div>
  </header>

  <main>
    <section class="hero">
      <div class="container">
        <h1>We design websites that people enjoy using</h1>
        <p>A small studio building fast, accessible and beautiful sites for growing businesses.</p>
        <a class="button" href="#contact">Start a project</a>
      </div>
    </section>

    <section class="section" id="services">
      <div class="container">
        <h2>What we do</h2>
        <div class="cards">
          <article class="card"><h3>Design</h3><p>Clear layouts and a brand that feels like you.</p></article>
          <article class="card"><h3>Development</h3><p>Hand-written, fast pages that work on every device.</p></article>
          <article class="card"><h3>Accessibility</h3><p>Sites everyone can use, with keyboard and screen reader support.</p></article>
          <article class="card"><h3>Performance</h3><p>Small images, clean code and top scores in speed tests.</p></article>
          <article class="card"><h3>SEO</h3><p>Semantic HTML and correct metadata so people find you.</p></article>
          <article class="card"><h3>Support</h3><p>We stay with you after launch.</p></article>
        </div>
      </div>
    </section>
  </main>

  <footer id="contact">
    <div class="container">
      <p>&copy; 2026 Northwind Studio &middot; <a href="mailto:hello@example.com">hello@example.com</a></p>
    </div>
  </footer>
</body>
</html>

Things to try: change --brand to your own colour; add a @media (min-width: 900px) rule that puts the header links in a different order; give the cards images with object-fit: cover; and use @container to lay out a card differently when it is wide. Then add behaviour (a theme toggle, a mobile menu) with the JavaScript tutorial.

17. Cheat sheet and FAQ

You want to… Use
Make sizes include padding *, *::before, *::after { box-sizing: border-box; }
Centre a box horizontally margin-inline: auto (with a width or max-width)
Centre anything both ways display: grid; place-items: center;
Space between flex or grid items gap: 1rem
A responsive grid of cards grid-template-columns: repeat(auto-fit, minmax(16rem, 1fr))
Push one flex item to the end margin-left: auto
Fluid font size clamp(1rem, 0.5rem + 2vw, 2rem)
Images that never overflow max-width: 100%; height: auto;
Crop an image to a box object-fit: cover
Dark mode Variables + @media (prefers-color-scheme: dark)
Sticky header position: sticky; top: 0;
Smooth hover effect transition on transform and opacity
Hide visually, keep for screen readers Use a utility class with position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%);

Quick answers

Should I use flexbox or grid? Both, together. Grid for the page and card galleries, flexbox for the components and for anything in a single line.

Do I still need Bootstrap or Tailwind? You never need them, and you will be much better at using them if you understand the CSS underneath. Plain modern CSS is now powerful enough for most sites.

Why does my CSS not apply? In order of likelihood: a typo in the property or value (check the warning in the Styles pane); a more specific rule wins (look for the struck-through line); the file is not loaded (wrong path, cached copy); the selector does not match the HTML; or the property does not work on that kind of element (for example width on an inline element).

How do I learn faster? Rebuild pages you like (just the layout), change one property at a time in the developer tools, and read MDN Web Docs (developer.mozilla.org). The games Flexbox Froggy and Grid Garden are fun ways to practise. Check what you built for speed with our page speed checker, and for SEO with the meta tag generator. Next: JavaScript, in our JavaScript tutorial. If you have not yet, read the HTML tutorial first.

Did you find this helpful?Tap the heart to let us know. It takes one second and no account.

More tutorials like this

Leave a Comment

Your email address will not be published. Required fields are marked *

Bigland Network IT

Practical tutorials for people who run, build and fix things: operating systems, databases, development, networking and security.

Topics

More

Site

© 2026 Bigland Network. All rights reserved.Always test commands on a non-production system first.
Scroll to Top