Skip to main content
Quick Reference

CSS Cheatsheet

Complete CSS3 quick reference — selectors, cascade, box model, flex, grid, typography, color, motion, responsive design, custom properties, and colorized snippets for fast revision.

Selectors

Colorized examples

* { /* universal */ }
h1, .title, #hero { color: teal; }
nav a { /* descendant */ }
ul > li { /* child */ }
h1 + p { /* adjacent sibling */ }
h1 ~ p { /* general sibling */ }
a[target="_blank"] { }
input[type^="text"] { }
:is(h1, h2, h3) { }
:where(.card) p { }
:not(.hidden) { }
:has(img) { }
SelectorMatchesExample
*Every element* { box-sizing: border-box; }
EElement typep, button
.classClass name.btn
#idUnique id#main
E FDescendantarticle p
E > FDirect childul > li
E + FNext siblingh2 + p
E ~ FFollowing siblingsh2 ~ p
[attr]Has attribute[disabled]
[attr=val]Exact value[type="email"]
[attr^=val]Starts with[href^="https"]
[attr$=val]Ends with[src$=".png"]
[attr*=val]Contains[class*="col-"]
[attr~=val]Space-separated list[class~="active"]
[attr|=val]Exact or prefix-[lang|=en]
:is() / :where()List (where = 0 specificity):is(h1, h2)
:not()Negation:not(.disabled)
:has()Relational parentform:has(:invalid)

Cascade, Specificity & Inheritance

/* Specificity: inline > ID > class/attr/pseudo > type/pseudo-element */
#nav .link:hover { /* 1,1,1 */ }
a:hover { color: red !important; }
@layer base, components, utilities;
@layer components {
  .btn { padding: .5rem 1rem; }
}
ConceptNotes
Origin orderUser agent → user → author; then layers; then specificity; then source order
Specificity(inline, IDs, classes/attrs/pseudos, types/pseudo-elements)
!importantOverrides normal rules in same origin (use sparingly)
@layerNamed cascade layers — later layers win over earlier
allinitial | inherit | unset | revert | revert-layer
Inheritedcolor, font-*, line-height, text-align, visibility, …
Not inheritedmargin, padding, border, width, display, …

Box Model

*, *::before, *::after {
  box-sizing: border-box;
}
.card {
  width: 320px;
  max-width: 100%;
  margin: 1rem auto;
  padding: 1rem 1.25rem;
  border: 2px solid #334155;
}
PropertyValues / notes
box-sizingcontent-box (default) | border-box (padding+border inside width)
width / heightauto, length, %, min-content, max-content, fit-content
min-* / max-*Constraints; min-height: 100dvh common for full viewport
margin1–4 values; auto centers block horizontally
padding1–4 values; no negative padding
overflowvisible | hidden | clip | scroll | auto
overflow-x/yAxis-specific overflow
aspect-ratioe.g. 16 / 9, 1
object-fitfill | contain | cover | none | scale-down
object-positione.g. center, top right

Display, Position & Flow

.badge { display: inline-block; }
.hidden { display: none; }
.sr-only {
  position: absolute;
  width: 1px; height: 1px;
  overflow: hidden; clip-path: inset(50%);
}
.sticky-bar {
  position: sticky;
  top: 0;
  z-index: 10;
}
PropertyKey values
displayblock | inline | inline-block | flex | inline-flex | grid | inline-grid | none | contents | flow-root
visibilityvisible | hidden | collapse
positionstatic | relative | absolute | fixed | sticky
top/right/bottom/leftOffsets for positioned elements
insetShorthand for top/right/bottom/left
z-indexStacking; only on positioned / flex / grid items
float / clearLegacy float layout; prefer flex/grid
isolationisolate creates stacking context

Flexbox

.row {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: space-between;
  align-items: center;
  gap: 1rem;
}
.row > * {
  flex: 1 1 200px; /* grow shrink basis */
}

Container

PropertyValues
flex-directionrow | row-reverse | column | column-reverse
flex-wrapnowrap | wrap | wrap-reverse
flex-flowdirection + wrap shorthand
justify-contentflex-start | flex-end | center | space-between | space-around | space-evenly
align-itemsstretch | flex-start | flex-end | center | baseline
align-contentMulti-line cross-axis packing
gap / row-gap / column-gapGutters between items

Items

PropertyValues
flex-growNumber — share of free space (default 0)
flex-shrinkNumber — shrink factor (default 1)
flex-basisInitial main size (auto, length, %)
flexShorthand: grow shrink basis — common: 1, 0 0 auto, 1 1 0%
align-selfOverride align-items for one item
orderInteger visual order (default 0)

CSS Grid

.layout {
  display: grid;
  grid-template-columns: repeat(12, 1fr);
  grid-template-rows: auto 1fr auto;
  gap: 1rem;
}
.sidebar { grid-column: 1 / 4; }
.main { grid-column: 4 / -1; }
.cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
}
PropertyNotes
grid-template-columns/rowsTrack list: 1fr, 200px, minmax(), repeat(), auto-fit/auto-fill
grid-template-areasNamed areas with ASCII art; items use grid-area
grid-auto-flowrow | column | dense
grid-auto-columns/rowsSize of implicit tracks
gapSame as flex
justify-items / align-itemsDefault alignment of cells
justify-content / align-contentAlign whole grid when spare space
grid-column / grid-rowstart / end lines; span N
grid-areaArea name or full line shorthand
place-items / place-content / place-selfAlign + justify shorthands
subgridgrid-template-*: subgrid inherits parent tracks

Typography

body {
  font-family: "Segoe UI", system-ui, sans-serif;
  font-size: 1rem;
  line-height: 1.6;
  font-weight: 400;
  letter-spacing: 0.01em;
  text-wrap: pretty;
}
h1 {
  font-size: clamp(1.75rem, 4vw + 1rem, 3rem);
  text-wrap: balance;
}
PropertyValues / notes
font-familyFont stack; last fallback serif/sans-serif/monospace
font-sizepx, rem, em, %, clamp()
font-weight100–900, normal, bold
font-stylenormal | italic | oblique
line-heightUnitless preferred (e.g. 1.5)
letter-spacing / word-spacingTracking / word gaps
text-alignstart | end | left | right | center | justify
text-decorationline | style | color | thickness shorthand
text-transformuppercase | lowercase | capitalize | none
text-overflowellipsis with overflow hidden + nowrap
white-spacenormal | nowrap | pre | pre-wrap | pre-line
@font-facefont-family, src, font-display

Color, Background & Images

:root {
  color-scheme: light dark;
  accent-color: #2563eb;
}
.hero {
  color: oklch(0.35 0.08 250);
  background:
    linear-gradient(135deg, #0ea5e9, #6366f1),
    url("/hero.jpg") center / cover no-repeat;
  opacity: 1;
}
Property / functionNotes
color / background-colorNamed, hex, rgb(), hsl(), oklch(), color-mix()
opacity0–1; affects whole element including children
background-imageurl(), gradients, multiple layers
background-sizecover | contain | lengths
background-positioncenter, percentages, keywords
background-repeatno-repeat | repeat | repeat-x/y
backgroundShorthand for layered backgrounds
background-clipborder-box | padding-box | content-box | text
filter / backdrop-filterblur(), brightness(), …
mix-blend-modeBlend with backdrop

Border, Outline & Shadow

.panel {
  border: 1px solid #cbd5e1;
  border-radius: 0.75rem;
  outline: 2px solid transparent;
  outline-offset: 2px;
  box-shadow: 0 8px 24px rgb(15 23 42 / 0.12);
}
.panel:focus-visible {
  outline-color: #2563eb;
}
PropertyNotes
borderwidth style color; also side longhands
border-stylesolid | dashed | dotted | double | none
border-radiusCorner radii
outlineOutside box; does not affect layout — use for focus rings
outline-offsetGap between outline and border edge
box-shadowoffset-x offset-y blur spread color
text-shadowShadow on glyphs

Transitions & Animations

.btn {
  transition: transform .2s ease, box-shadow .2s ease;
}
.btn:hover { transform: translateY(-2px); }

@keyframes fade-in {
  from { opacity: 0; }
  to { opacity: 1; }
}
.enter {
  animation: fade-in .4s ease both;
}

@media (prefers-reduced-motion: reduce) {
  * { animation: none; transition: none; }
}
PropertyNotes
transitionproperty duration timing delay shorthand
transition-propertyPrefer listing properties over all
transition-timing-functionease, linear, cubic-bezier(), steps()
animationFull shorthand for keyframe animations
animation-name@keyframes name
animation-iteration-countNumber or infinite
animation-directionnormal | reverse | alternate
animation-fill-modenone | forwards | backwards | both
animation-play-staterunning | paused

Transforms

.tilt {
  transform:
    translate(10px, -4px)
    rotate(-2deg)
    scale(1.05);
  transform-origin: center;
  perspective: 800px;
}
Function / propertyNotes
translate() / translateX/Y/ZMove without affecting layout flow
scale() / scaleX/YResize visually
rotate() / rotateX/Y/ZAngle (deg, turn, rad)
skew()Skew axes
transform-originPivot point
transform-styleflat | preserve-3d
perspective3D depth on parent
backface-visibilityvisible | hidden

Responsive & Media Queries

.container {
  width: min(100% - 2rem, 72rem);
  margin-inline: auto;
}

@media (width >= 768px) {
  .nav { display: flex; }
}

@container card (min-width: 400px) {
  .card-body { display: grid; grid-template-columns: 1fr 1fr; }
}
FeatureNotes
@media (min-width)Classic breakpoints; also range syntax (width >= 768px)
@media (prefers-color-scheme)light | dark
@media (prefers-reduced-motion)Respect accessibility
@media (hover: hover)True hover capability
@containerContainer queries; parent needs container-type
Viewport unitsvw, vh, dvh, svh, lvh
Logical propsmargin-inline, padding-block, inset-inline-start

Pseudo-classes & Pseudo-elements

a:hover, a:focus-visible { text-decoration: underline; }
li:nth-child(odd) { background: #f1f5f9; }
input:invalid { border-color: crimson; }
.card::before {
  content: "";
  position: absolute;
  inset: 0;
}
::selection { background: #93c5fd; }

Common pseudo-classes

SelectorWhen
:hover :active :focus :focus-visible :focus-withinInteraction / focus
:visited :link :any-linkLinks
:checked :disabled :enabled :requiredForm state
:valid :invalid :placeholder-shownValidation
:first-child :last-child :nth-child()Structure
:first-of-type :nth-of-type() :empty :rootType / document
:target :modal :popover-openUI state

Pseudo-elements

SelectorNotes
::before / ::afterGenerated content — needs content
::placeholderInput placeholder text
::selectionSelected text
::markerList marker
::first-line / ::first-letterTypography flourishes
::backdropDialog / fullscreen backdrop

Custom Properties & Functions

:root {
  --brand: #2563eb;
  --space: 1rem;
  --radius: 0.5rem;
}
.btn {
  background: var(--brand, #1d4ed8);
  padding: calc(var(--space) * 0.75) var(--space);
  border-radius: var(--radius);
}
FeatureNotes
--nameCustom property; inherits; set on any element
var(--name, fallback)Read variable with optional fallback
calc()Arithmetic with mixed units
min() / max() / clamp()Responsive sizing without breakpoints
@propertyTyped custom properties (animatable)
@supportsFeature queries
@import / @layer / @scopeModule / cascade / scoped styling

Gotchas & Interview Tips

  • Prefer border-box globally — width includes padding and border.
  • Margin collapse: vertical margins between siblings/parent-child can merge; flex/grid/padding/border stop it.
  • absolute positions relative to nearest positioned ancestor (not always the parent).
  • z-index only works on positioned / flex / grid items; new stacking contexts from opacity, transform, filter.
  • Use rem for typography and spacing; em for component-relative sizing.
  • Never remove focus outlines without a visible :focus-visible replacement.
  • :has(), container queries, and oklch() are modern — check support if you must support old browsers.
  • Shorthands reset omitted longhands (e.g. background: red clears image/layers).

Next: CSS tutorial · Cheatsheet hub · HTML cheatsheet