Skip to content
Tutorials Center
My learning

Topics

Lesson 136 of 139 ยท Practice and Review

CSS Cheat Sheet

A one-page CSS cheat sheet with selectors, specificity, units, the box model, flexbox, grid, responsive design, animation and modern CSS, with live examples.

This page packs the whole CSS course into one place you can scan in a few minutes. Every section is a compact reminder, not a full explanation: each one links to the lesson that teaches the topic properly, with live examples and the reasoning behind the rules.

Use it when you know what you want but can't remember the exact property name, value order or selector syntax. The few live editors on the page cover the items people look up most often: alignment in flexbox and grid, fluid sizing, and the modern selectors.

Basics

Rule anatomy

CSS
selector {
  property: value;        /* a declaration */
  margin: 0 auto;         /* shorthand: several values */
}

/* comment โ€” the only comment style in CSS */

Adding CSS to a page

Method Code Use for
External file <link rel="stylesheet" href="styles.css"> Almost everything
<style> element <style> p { color: navy; } </style> Small pages, critical CSS
style attribute <p style="color: navy"> Values set by scripts, custom properties

More: Adding CSS to a Page, CSS Syntax.

Selectors

Selector Matches Specificity
* every element (0, 0, 0)
p every <p> (0, 0, 1)
.card class="card" (0, 1, 0)
#main id="main" (1, 0, 0)
[type="email"] attribute equals (0, 1, 0)
[href^="https"], [href$=".pdf"], [class*="btn"] starts with, ends with, contains (0, 1, 0)
a, button either (a selector list) each scored on its own
nav a <a> anywhere inside <nav> sum of parts
ul > li direct children only sum of parts
h2 + p the <p> right after an <h2> sum of parts
h2 ~ p every <p> after an <h2>, same parent sum of parts

Pseudo-classes and pseudo-elements

CSS
a:hover, a:focus-visible { }      /* user actions */
input:checked, input:disabled { } /* form states */
input:user-invalid { }            /* invalid, after the user has interacted */
li:first-child, li:last-child { }
li:nth-child(odd), li:nth-child(3n + 1) { }
p:first-of-type, p:only-child { }
:is(h1, h2, h3) a { }             /* takes the highest specificity inside */
:where(h1, h2, h3) a { }          /* specificity 0 inside :where() */
.card:not(.featured) { }
.card:has(img) { }                /* a card that contains an image */
p::first-line, p::first-letter { }
.icon::before { content: "โ†’ "; }  /* needs content to appear */
li::marker, ::selection, input::placeholder { }

More: Selector Basics, Combinators, Pseudo-classes, Pseudo-elements, :is(), :where(), :not() and :has().

Modern selectors at work

The cascade

When rules conflict, the browser compares them in this order and stops at the first difference:

  1. Origin and importance (user-agent, user, author; !important reverses the order)
  2. Inline style attribute beats any selector
  3. Cascade layers (@layer): later layers win; unlayered styles beat layered ones
  4. Specificity: compare (IDs, classes/attributes/pseudo-classes, types/pseudo-elements) left to right
  5. Order of appearance: the last rule wins
CSS
@layer reset, base, components, utilities;  /* declare the order once */
@layer components { .btn { padding: 8px 16px; } }

color: inherit;   /* take the parent's value */
color: initial;   /* the property's spec default */
color: unset;     /* inherit if inherited property, else initial */
color: revert;    /* back to the browser's default style */

Inherited by default: color, font-*, line-height, text-align, letter-spacing, visibility, cursor, list-style. Not inherited: box model, backgrounds, borders, display, position, layout.

More: How the Cascade Works, Specificity, Inheritance, Cascade Layers, Global Values.

Values and units

Unit Relative to Typical use
px a reference pixel borders, shadows, small fixed details
rem root font size (usually 16px) font sizes, spacing
em the element's own font size padding that scales with text, icons
% the parent (depends on property) widths
vw / vh 1% of the viewport width / height full-screen sections
svh / lvh / dvh small / large / dynamic viewport height mobile-safe full height
ch width of "0" in the font readable line length (max-width: 65ch)
fr a share of free space (grid only) grid tracks
cqi 1% of the query container's inline size container-based sizing
CSS
width: calc(100% - 2rem);
font-size: clamp(1rem, 0.8rem + 1vw, 1.5rem);  /* min, preferred, max */
width: min(100%, 60rem);                       /* the smaller one */
padding: max(1rem, 3vw);                       /* the larger one */

:root { --brand: #2563eb; --space: 1rem; }     /* custom properties */
.btn  { background: var(--brand); padding: var(--space, 12px); }

Colors

CSS
color: #1e293b;                       /* hex */
color: rgb(30 41 59 / 80%);           /* space-separated, with alpha */
color: hsl(220 40% 20%);
color: oklch(60% 0.15 250);           /* perceptual lightness, chroma, hue */
background: color-mix(in oklch, var(--brand), white 30%);
border-color: currentColor;           /* the element's text color */

More: Units, Viewport Units, Colors, Modern Color, calc(), min(), max() and clamp(), Custom Properties.

Fluid sizing with clamp() and min()

The box model

CSS
*, *::before, *::after { box-sizing: border-box; }  /* width includes padding + border */

margin: 10px;               /* all sides */
margin: 10px 20px;          /* block (top/bottom)  inline (left/right) */
margin: 10px 20px 30px;     /* top  inline  bottom */
margin: 10px 20px 30px 40px;/* top right bottom left (clockwise) */
margin-inline: auto;        /* center a block with a width */
padding-block: 1rem;        /* logical: top and bottom in horizontal text */

border: 2px solid #cbd5e1;
border-radius: 12px;        /* 50% for a circle on a square */
outline: 3px solid #2563eb; outline-offset: 2px;  /* takes no space */
box-shadow: 0 4px 12px rgb(0 0 0 / 15%);          /* x y blur color */
box-shadow: inset 0 0 0 2px #2563eb;              /* inner "border" */

overflow: auto;             /* scrollbars only when needed */
aspect-ratio: 16 / 9;
  • Vertical margins between blocks collapse (the larger wins); flex and grid items don't collapse.
  • max-width stops growth; min-height lets content grow past a size.

More: The Box Model, box-sizing, Margins, Padding, Borders, Overflow.

Text and fonts

CSS
font: italic 600 1.125rem/1.5 system-ui, sans-serif;  /* style weight size/line-height family */
font-family: "Inter", system-ui, sans-serif;          /* always end with a generic family */
line-height: 1.5;            /* unitless: scales with font size */
text-align: center;          /* start | end | center | justify */
text-transform: uppercase;
letter-spacing: 0.05em;
text-decoration: underline wavy #dc2626;
text-wrap: balance;          /* even lines for headings */
overflow-wrap: anywhere;     /* break long URLs */
white-space: nowrap; overflow: hidden; text-overflow: ellipsis;  /* one-line truncation */

@font-face {
  font-family: "Brand";
  src: url("/fonts/brand.woff2") format("woff2");
  font-display: swap;
}

More: Styling Text, Fonts, Web Fonts, Line Height, Wrapping, Overflow and Hyphens.

Backgrounds and effects

CSS
background: #f8fafc url("bg.svg") no-repeat center / cover;  /* color image repeat position / size */
background-image: linear-gradient(135deg, #2563eb, #9333ea);
background-image: radial-gradient(circle at top, #fde68a, transparent 60%);
background-clip: text; color: transparent;   /* gradient text */

img { object-fit: cover; aspect-ratio: 1; }  /* crop to fill */
filter: blur(4px) grayscale(1);
backdrop-filter: blur(8px);                  /* frosted glass */
mix-blend-mode: multiply;
clip-path: circle(50%);
opacity: 0.5;                                 /* whole element, including children */

More: Backgrounds, Gradients, object-fit and aspect-ratio, Filters, Blend Modes, Clip Paths and Masks.

Display and positioning

display Behavior
block new line, full width, accepts width/height
inline flows in text, ignores width/height
inline-block flows in text, accepts width/height
flex / inline-flex flex container
grid / inline-grid grid container
none removed from layout and accessibility tree
contents the box disappears, children stay
position Offsets relative to In normal flow?
static (offsets ignored) yes
relative its own normal spot yes
absolute nearest positioned ancestor no
fixed the viewport no
sticky its scroll container, once a threshold is crossed yes
CSS
.overlay { position: absolute; inset: 0; }  /* top/right/bottom/left: 0 */
.modal   { position: fixed; z-index: 10; }  /* z-index: positioned elements, flex and grid items */
.header  { position: sticky; top: 0; }

/* Center anything */
.parent { display: grid; place-items: center; }

More: The display Property, Positioning, z-index and Stacking Contexts, Centering Anything.

Flexbox

Container property Common values
flex-direction row ยท column ยท row-reverse
flex-wrap nowrap ยท wrap
justify-content (main axis) flex-start ยท center ยท space-between ยท space-around ยท space-evenly
align-items (cross axis) stretch ยท center ยท flex-start ยท flex-end ยท baseline
align-content (wrapped lines) same as justify-content, plus stretch
gap 1rem ยท 8px 16px (row column)
Item property What it does
flex: 1 grow to share free space equally (1 1 0%)
flex: none keep its size (0 0 auto)
flex: 0 0 200px grow, shrink, basis
align-self override align-items for one item
order visual order only (keep DOM order logical)
margin-left: auto push this item and the rest to the end
min-width: 0 let an item shrink below its content (fixes overflow)
Flexbox alignment playground

More: Flexbox Basics, Flex Container Properties, Flex Item Properties, Flexbox Patterns.

Grid

CSS
.grid {
  display: grid;
  grid-template-columns: 200px 1fr;                          /* fixed + flexible */
  grid-template-columns: repeat(3, 1fr);                     /* three equal columns */
  grid-template-columns: repeat(auto-fit, minmax(14rem, 1fr)); /* responsive, no media query */
  grid-template-rows: auto 1fr auto;                         /* header, content, footer */
  gap: 1rem;
}

.item { grid-column: 1 / -1; }       /* span from first to last line */
.item { grid-column: span 2; }       /* span two tracks */
.item { grid-area: 2 / 1 / 4 / 3; }  /* row-start / col-start / row-end / col-end */

.page {
  grid-template-areas:
    "header header"
    "nav    main"
    "footer footer";
}
.page > header { grid-area: header; }

.cards > article { display: grid; grid-template-rows: subgrid; grid-row: span 3; }
Alignment Aligns Applies to
justify-items / justify-self items in their cells, inline axis container / item
align-items / align-self items in their cells, block axis container / item
justify-content / align-content the whole grid inside the container container
place-items: center both axes at once container

More: Grid Basics, Grid Tracks, Placing Grid Items, Grid Template Areas, Grid Alignment, Subgrid, Grid Patterns.

Responsive design

HTML
<meta name="viewport" content="width=device-width, initial-scale=1">
CSS
/* Mobile first: base styles for small screens, then add */
@media (width >= 48rem) { .layout { grid-template-columns: 16rem 1fr; } }
@media (prefers-color-scheme: dark) { :root { --bg: #0f172a; } }
@media (prefers-reduced-motion: reduce) { * { animation-duration: 0.01ms !important; } }
@media (hover: hover) and (pointer: fine) { .card:hover { translate: 0 -2px; } }
@media print { nav { display: none; } }

/* Container queries: respond to the component's own width */
.card-wrap { container-type: inline-size; }
@container (width > 30rem) { .card { display: flex; } }

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

More: Responsive Design Principles, Media Queries, Mobile-First CSS, Container Queries, Fluid Typography, Dark Mode.

Transitions, transforms and animation

CSS
.btn { transition: background-color 200ms ease, transform 200ms ease; }
.btn:hover { transform: translateY(-2px) scale(1.02); }

/* Individual transform properties (no need to repeat the whole transform) */
.icon { rotate: 45deg; scale: 1.2; translate: 10px 0; }

@keyframes fade-in {
  from { opacity: 0; translate: 0 8px; }
  to   { opacity: 1; translate: 0 0; }
}
.toast { animation: fade-in 300ms ease-out both; }
/* name duration timing-function delay iteration-count direction fill-mode */
  • Animate transform and opacity for smooth motion; avoid animating width, top or margin.
  • transition describes how a change animates; the change itself comes from a state such as :hover or a class.

More: Transitions, 2D Transforms, Keyframe Animations, Motion and prefers-reduced-motion.

Modern CSS

CSS
.card {                        /* native nesting */
  padding: 1rem;
  & h2 { margin-top: 0; }
  &:hover { border-color: var(--brand); }
  @media (width >= 40rem) { padding: 2rem; }
}

@supports (display: grid) { }              /* feature queries */
@supports not (anchor-name: --a) { }

@scope (.card) to (.card__body) { p { color: gray; } }  /* scoped styles */

html { scroll-behavior: smooth; }
.carousel { scroll-snap-type: x mandatory; }
.carousel > * { scroll-snap-align: start; }

More: CSS Nesting, Feature Queries, Scroll Snap, Anchor Positioning, @scope.

Accessibility and good habits

CSS
:focus-visible { outline: 3px solid #2563eb; outline-offset: 2px; }  /* never remove focus without a replacement */

.visually-hidden {                 /* hidden on screen, still read aloud */
  position: absolute; width: 1px; height: 1px;
  overflow: hidden; clip-path: inset(50%); white-space: nowrap;
}
  • Text contrast of at least 4.5:1 (3:1 for large text); don't use color alone to show meaning.
  • Keep DOM order and visual order the same; order and grid placement don't change tab order.
  • Use a small reset, low specificity (classes, :where(), layers) and a naming convention.

More: Accessible CSS, Organizing CSS, Resets and Base Styles, CSS Performance.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which selector has the highest specificity?

    #nav a is (1, 0, 1). One ID beats any number of classes; :where() contributes zero.
  2. 2. Which declaration makes a responsive card grid without a media query?

    auto-fit with minmax() fits as many columns of at least 14rem as the space allows and stretches them to fill the row.
  3. 3. What does margin: 10px 20px 30px; set?

    With three values, the middle one is used for both inline sides (left and right).
  4. 4. Which properties are the safest to animate for smooth motion?

    Browsers can usually animate transform and opacity without recalculating layout, so they stay smooth.

Summary

  • Selectors, the cascade order (origin, layers, specificity, order) and inheritance decide which value wins.
  • Prefer rem for sizes, clamp() and min() for fluid values, and custom properties for anything you repeat.
  • box-sizing: border-box, shorthand order (top, right, bottom, left) and logical properties cover most box-model work.
  • Flexbox lays out one direction; grid lays out rows and columns. gap works in both.
  • Build mobile first, then add media queries and container queries; respect user preferences like reduced motion and dark mode.
  • Keep focus styles visible, contrast high and specificity low.

Next: CSS Recipes Gallery.