CSS Cheat Sheet

The CSS properties, selectors and layout tools you reach for every day, each explained in a line or two. Use the search box to find anything fast.

173 quick references · 20 sections · Updated October 2026

Adding CSS and syntax

Full lesson
selector { property: value; }
A CSS rule. The selector picks elements, each declaration inside the braces styles them.
<link rel="stylesheet" href="style.css">
External CSS file. The best option: one file styles every page and the browser caches it.
<style> in the head
Internal CSS that applies to one page only.
style="" attribute
Inline CSS on one element. Highest priority, hardest to maintain.
/* comment */
A CSS comment. CSS has no single-line comment syntax.

Basic selectors

Full lesson
p
Type selector: every <p> element.
.card
Class selector: every element with class="card".
#header
ID selector: the one element with id="header".
*
Universal selector: every element.
h1, h2, h3
Grouping: apply the same rules to several selectors.
nav a
Descendant: any <a> anywhere inside <nav>.
ul > li
Child: only <li> elements directly inside <ul>.
h2 + p
Adjacent sibling: the <p> immediately after an <h2>.
h2 ~ p
General sibling: every <p> after the <h2> with the same parent.
a[href^="https"]
Attribute selector. Also [attr], [attr="x"], [attr$="x"] (ends with) and [attr*="x"] (contains).
color
Sets the text color.
background-color
Sets the background color.
red, tomato, navy
Named colors. There are about 140 of them.
#ff6600 or #f60
Hex color: red, green and blue in two digits each (or one when doubled).
rgb(255 102 0)
Red, green and blue from 0 to 255.
hsl(24 100% 50%)
Hue (0 to 360), saturation and lightness. The easiest format to tweak by hand.
rgb(0 0 0 / 50%)
The slash adds alpha transparency to rgb() and hsl().
currentColor
Reuses the element's current text color for borders, icons and so on.
opacity
Makes the whole element, including its children, transparent: 0 to 1.

Text and fonts

Full lesson
font-family
The font stack, with fallbacks: font-family: "Inter", system-ui, sans-serif.
font-size
The size of the text. Prefer rem so it respects the user's settings.
font-weight
Boldness: 400 is normal, 700 is bold. Variable fonts allow any value in between.
font-style
normal or italic.
line-height
Space between lines. A unitless 1.5 is a good default for body text.
text-align
left, right, center or justify.
text-decoration
underline, line-through or none. Often used to remove link underlines.
text-transform
uppercase, lowercase or capitalize.
letter-spacing
Space between letters. word-spacing does the same for words.
text-overflow: ellipsis
Shows … for clipped text. Needs overflow: hidden and white-space: nowrap too.
@font-face
Loads a custom font file. Add font-display: swap so text stays visible while it loads.

Units and values

Full lesson
px
Fixed pixels. Good for borders and shadows.
rem
Relative to the root font size (usually 16px). Best for font sizes and spacing.
em
Relative to the element's own font size. Compounds when nested.
%
A percentage of the parent's matching value.
vw and vh
1% of the viewport width or height.
dvh
Viewport height that adjusts for mobile browser toolbars. Better than vh for full-screen sections.
ch
Width of the "0" character. max-width: 65ch gives readable line lengths.
calc()
Do maths with mixed units: width: calc(100% - 2rem).
min(), max(), clamp()
Pick the smaller, larger, or a value kept between a minimum and maximum.

Box model and sizing

Full lesson
content, padding, border, margin
Every element is a box. Padding is inside the border, margin is outside.
padding
Space between the content and the border. Shorthand: top right bottom left.
margin
Space outside the border. Can be negative.
margin: 0 auto
Centers a block element that has a set width.
margin collapse
Vertical margins between neighbouring blocks merge into the larger one.
border
Shorthand for width, style and color: border: 1px solid #ccc.
width and height
The content size, unless box-sizing is border-box.
max-width and min-width
Limits for width. max-width: 100% keeps images inside their container.
box-sizing: border-box
Includes padding and border in the width. Apply to everything with *, *::before, *::after.
overflow
What happens to content that does not fit: visible, hidden, scroll or auto.

Backgrounds, borders and shadows

Full lesson
background-image
Uses an image or gradient as the background: url("pic.jpg").
background-size
cover fills the box (cropping if needed), contain fits the whole image.
background-position
Where the image sits, e.g. center or top right.
background-repeat
repeat (default) or no-repeat.
linear-gradient()
A color fade: linear-gradient(to right, #6558d9, #f5a623). radial-gradient() is circular.
border-radius
Rounds corners. 50% turns a square into a circle.
box-shadow
Adds a shadow: x-offset y-offset blur color. Add the inset keyword for an inner shadow.
outline
A line drawn outside the border that does not take up space. Used for focus rings.

Reset and defaults

Full lesson
*, *::before, *::after { box-sizing: border-box }
The most common reset line.
body { margin: 0 }
Removes the default 8px margin around the page.
img { max-width: 100%; height: auto; display: block }
Makes images responsive and removes the gap below them.
inherit, initial, unset
Take the parent's value, the browser default, or whichever of those applies.

Pseudo-classes and pseudo-elements

Full lesson
:hover
While the mouse is over the element.
:focus
While the element has keyboard or click focus.
:focus-visible
Focus shown only when the browser thinks a focus ring is needed, such as keyboard use.
:active
While the element is being pressed.
:first-child and :last-child
The first or last child of its parent.
:nth-child(2n)
Every second child. Also odd, even, 3 and 3n+1.
:not(.x)
Everything that does not match the selector inside.
:checked, :disabled, :required
Form states.
:valid and :invalid
Styles for fields that pass or fail validation.
::before and ::after
Insert generated content before or after an element. Needs the content property.
::placeholder
Styles the hint text of an input.
::selection
Styles highlighted text.
::first-line, ::first-letter
Styles the first line or letter of a block.

Specificity and the cascade

Full lesson
specificity order
Inline style beats id, which beats class/attribute/pseudo-class, which beats element selectors.
source order
When specificity ties, the rule written last wins.
inheritance
Text properties (color, font, line-height) pass to children. Box properties (margin, border) do not.
!important
Overrides normal specificity. Use it only as a last resort.
@layer
Group rules in layers where a later layer always beats an earlier one, whatever the specificity.

Display and position

Full lesson
display: block
Starts on a new line and fills the width.
display: inline
Flows with text. Width, height and vertical margin are ignored.
display: inline-block
Flows with text but accepts width, height and margins.
display: none
Removes the element from the page entirely. visibility: hidden hides it but keeps its space.
position: static
The default, normal flow. top, left and z-index do nothing.
position: relative
Stays in flow, can be nudged with top/left, and becomes the anchor for absolute children.
position: absolute
Removed from flow and placed relative to the nearest positioned ancestor.
position: fixed
Stays fixed relative to the screen while scrolling.
position: sticky
Scrolls normally, then sticks at a set offset like top: 0. See the sticky lesson.
top, right, bottom, left, inset
Offsets for positioned elements. inset: 0 sets all four.
z-index
Stacking order of positioned elements. Higher is on top.
display: flex
Makes the element a flex container. Its children become flex items.
flex-direction
The main axis: row (default), column, row-reverse or column-reverse.
justify-content
Aligns items along the main axis: flex-start, center, space-between, space-around, space-evenly.
align-items
Aligns items along the cross axis: stretch (default), center, flex-start, flex-end, baseline.
flex-wrap
wrap lets items move to a new line instead of shrinking.
gap
Space between items. Cleaner than margins.
align-content
Aligns the lines themselves when items wrap onto several lines.
flex: 1
Shorthand for grow 1, shrink 1, basis 0. The item shares the free space equally.
flex-grow
How much of the extra space an item takes compared with its siblings.
flex-shrink
How much an item shrinks when space runs out. 0 stops it shrinking.
flex-basis
The starting size of an item before growing or shrinking.
align-self
Overrides align-items for one item.
order
Changes the visual order of items. It does not change the tab order.
margin-left: auto
Pushes an item (and everything after it) to the far end, perfect for a navbar.
centering
display: flex; justify-content: center; align-items: center; centers anything.
display: grid
Makes the element a grid container with rows and columns.
grid-template-columns
Defines the columns, e.g. 200px 1fr 1fr.
grid-template-rows
Defines the rows. Rows are created automatically if you leave it out.
fr unit
A fraction of the free space. 1fr 2fr gives the second column twice the width.
repeat(3, 1fr)
Writes repeated tracks in a short form.
minmax(200px, 1fr)
A track that is never smaller than 200px and grows to share space.
repeat(auto-fit, minmax(240px, 1fr))
A responsive grid that fits as many columns as possible, no media queries needed.
gap
Space between rows and columns. row-gap and column-gap set them separately.
grid-column: 1 / 3
Place an item from line 1 to line 3. Use span 2 to cover two tracks.
grid-row
Same as grid-column, for rows.
grid-template-areas
Draw the layout with names: "header header" "sidebar main".
grid-area
Puts an item into a named area.
place-items
Shorthand for align-items and justify-items. place-content aligns the whole grid.
grid-auto-flow: dense
Lets later items fill earlier gaps.
Flexbox vs Grid
Flexbox arranges items in one direction. Grid arranges rows and columns together.

Responsive design

Full lesson
<meta name="viewport" ...>
Required in the HTML head, otherwise phones show a zoomed-out desktop page.
@media (min-width: 768px)
Applies styles from 768px upward. Write mobile styles first, then add these.
@media (max-width: 600px)
Applies styles at 600px and below.
@media (prefers-color-scheme: dark)
Applies when the visitor's device is in dark mode.
@media (prefers-reduced-motion: reduce)
Applies when the visitor asks for less animation.
mobile-first
Start with the small-screen layout and add complexity with min-width queries.
clamp(1rem, 2.5vw, 2rem)
A fluid value with a minimum, a preferred size and a maximum.
@container (min-width: 400px)
Responds to the size of the parent container, not the screen. Needs container-type: inline-size.
aspect-ratio: 16 / 9
Keeps a box at a fixed shape as its width changes.
object-fit: cover
Makes an image or video fill its box without distortion.

Variables and theming

Full lesson
:root { --brand: #6558d9; }
Defines a custom property (CSS variable) available everywhere.
var(--brand)
Uses a variable. A fallback can follow: var(--brand, blue).
scoped variables
Redefine a variable on one element and everything inside it changes.
color-scheme: light dark
Tells the browser the page supports both themes so form controls and scrollbars match.
[data-theme="dark"]
A common way to switch themes: redefine the variables under this selector.
light-dark()
Pick a color for light mode and one for dark mode in a single value.

Transitions, transforms and animations

Full lesson
transition
Animates a change smoothly: transition: background 0.2s ease.
transform: translate(10px, 20px)
Moves an element without affecting the layout.
transform: scale(1.1)
Makes an element bigger or smaller.
transform: rotate(45deg)
Rotates an element.
transform-origin
The point a transform pivots around.
@keyframes name { ... }
Defines the steps of an animation.
animation
Plays keyframes: animation: spin 1s linear infinite.
animation-fill-mode: forwards
Keeps the final state of an animation when it ends.
will-change
A hint that a property will animate. Use rarely, only when you have measured a problem.

Modern selectors, nesting and layers

Full lesson
:is(h1, h2, h3)
Matches any selector in the list. Shortens repeated selectors.
:where()
Same as :is() but adds zero specificity.
:has(img)
Selects a parent that contains a match, e.g. a card that has an image.
& (nesting)
Write child and state rules inside the parent rule: .card { &:hover { ... } }.
@layer base, components;
Declares the layer order once, then fills each layer with rules.
@supports (display: grid)
Applies rules only if the browser supports a feature.
@import
Pulls in another stylesheet. Slow for performance, so prefer separate link tags or a build step.

Architecture and naming

Full lesson
BEM
Block, Element, Modifier naming: .card, .card__title, .card--featured.
keep selectors flat
Prefer one class over long chains like .a .b .c, so rules stay easy to override.
utility classes
Tiny single-purpose classes such as .visually-hidden or .text-center.
file order
Reset, variables, base, layout, components, utilities.

Performance and accessibility

Full lesson
visible focus
Always keep a clear :focus-visible style for keyboard users.
color contrast
Normal text needs a contrast ratio of at least 4.5:1 with its background.
prefers-reduced-motion
Turn off or shorten large animations for people who ask for it.
animate transform and opacity
These are cheap for the browser. Avoid animating width, height or top.
.visually-hidden
Hides text visually but keeps it for screen readers.
minify and combine
Ship one small CSS file for production and avoid long @import chains.

More cheat sheets