CSS Cheat Sheet
Every property, selector, and rule - searchable, copy-ready, with live previews.
p { color: #333; }
.card { border-radius: 8px; }
#header { background: #fff; }* { margin: 0; padding: 0; }h1, h2, h3 { font-weight: 600; }nav a { text-decoration: none; } /* descendant */
ul > li { list-style: none; } /* direct child */
h2 + p { margin-top: 0; } /* adjacent sibling */
h2 ~ p { color: #555; } /* general sibling */a:hover { color: blue; }
a:visited { color: purple; }
input:focus { outline: 2px solid blue; }
button:active { opacity: .8; }
input:disabled { opacity: .4; }
input:checked + label { font-weight: bold; }li:first-child { margin-top: 0; }
li:last-child { margin-bottom: 0; }
li:nth-child(odd) { background: #f5f5f5; }
li:nth-child(3n+1) { font-weight: bold; }
li:only-child { font-size: 1.2rem; }button:not(.disabled) { cursor: pointer; }
:is(h1, h2, h3) { line-height: 1.2; }
:where(section, article) p { font-size: 1rem; }
a:has(img) { display: block; }.card::before { content: ''; display: block; height: 4px; background: purple; }
input::placeholder { color: #aaa; }
::selection { background: #7c6dff; color: #fff; }
p::first-line { font-weight: bold; }
p::first-letter { font-size: 2em; float: left; }[type="text"] { border: 1px solid #ccc; }
[href^="https"] { color: green; }
[href$=".pdf"] { color: red; }
[class*="icon"] { display: inline-flex; }
[lang|="en"] { font-family: serif; }*, *::before, *::after { box-sizing: border-box; }
* { margin: 0; }
body { line-height: 1.5; -webkit-font-smoothing: antialiased; }
img, picture, video, canvas, svg { display: block; max-width: 100%; }
input, button, textarea, select { font: inherit; }
p, h1, h2, h3, h4, h5, h6 { overflow-wrap: break-word; }
#root, #__next { isolation: isolate; }margin: 10px 20px 10px 20px; padding: 8px 16px; margin: 0 auto;
margin-inline: auto; margin-block: 1.5rem; padding-inline: 1rem 2rem; padding-inline-start: 1rem;
.card { width: 100%; max-width: 600px; min-height: 200px; }
.video { aspect-ratio: 16 / 9; width: 100%; }
inline-size: 100%;
block-size: 200px;border: 1px solid #ccc; border-radius: 8px; border-top: 3px solid purple; border-block: 1px solid #ccc; border-inline: 1px solid #ccc;
:focus-visible {
outline: 2px solid #7c6dff;
outline-offset: 3px;
}box-shadow: 0 4px 16px rgba(0,0,0,.12); box-shadow: inset 0 2px 4px rgba(0,0,0,.1); box-shadow: 0 1px 3px rgba(0,0,0,.1), 0 8px 24px rgba(0,0,0,.08);
overflow: hidden | auto | scroll | visible; overflow-x: hidden; overflow-y: scroll; overflow: clip;
inset: 0; inset-inline: 0; inset-block: 0;
font: italic 600 1.125rem/1.6 'Inter', sans-serif;
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;600&display=swap');@font-face {
font-family: 'MyFont';
src: url('myfont.woff2') format('woff2');
font-weight: 400;
font-display: swap;
}font-size: clamp(1rem, 2.5vw, 2rem);
font-variant-numeric: tabular-nums; font-variant-numeric: oldstyle-nums; font-variant-numeric: diagonal-fractions; font-variant-numeric: ordinal;
font-variant: small-caps; font-variant: all-small-caps;
font-feature-settings: "liga" 1; font-feature-settings: "tnum" 1; font-feature-settings: "frac" 1; font-feature-settings: "smcp" 1;
text-align: center | left | right | justify; letter-spacing: .05em; line-height: 1.6; text-transform: uppercase | lowercase | capitalize; text-decoration: underline dotted #7c6dff;
.truncate { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.clamp-3 {
display: -webkit-box;
-webkit-line-clamp: 3;
-webkit-box-orient: vertical;
overflow: hidden;
}overflow-wrap: break-word; word-break: break-all; word-break: keep-all; hyphens: auto;
h1, h2, h3 { text-wrap: balance; }
p { text-wrap: pretty; }pre, code { tab-size: 2; }writing-mode: vertical-rl; writing-mode: vertical-lr; text-orientation: mixed; text-orientation: upright;
list-style: none;
list-style: square inside;
li::marker { color: #7c6dff; font-size: .8em; content: '>> '; }color: #7c6dff; color: rgb(124, 109, 255); color: rgba(124, 109, 255, .5); color: hsl(248, 100%, 71%); color: oklch(0.65 0.22 280); color: currentColor;
background: color-mix(in srgb, #7c6dff 60%, white); color-scheme: light dark; color: light-dark(#1e2022, #f0eff8);
background: url('img.jpg') center/cover no-repeat #f0f;background: linear-gradient(135deg, #7c6dff 0%, #ec4899 100%);
background: radial-gradient(circle at center, #7c6dff, transparent); background: conic-gradient(from 0deg, #7c6dff, #ec4899, #10b981, #7c6dff);
filter: blur(4px); filter: brightness(1.2) contrast(1.1) saturate(1.5); filter: grayscale(100%); filter: drop-shadow(2px 4px 8px rgba(0,0,0,.4));
.glass {
background: rgba(255,255,255,.15);
backdrop-filter: blur(12px) saturate(1.8);
border: 1px solid rgba(255,255,255,.2);
}display: flex; flex-direction: row | column | row-reverse | column-reverse; flex-wrap: nowrap | wrap; flex-flow: row wrap; gap: 16px; gap: 8px 24px;
justify-content: flex-start | flex-end | center | space-between | space-evenly; align-items: stretch | flex-start | flex-end | center | baseline;
.center { display: flex; align-items: center; justify-content: center; }flex: 1; flex: 0 0 200px; flex: 1 1 auto;
.item { align-self: flex-end; }
.first { order: -1; }
.last { order: 999; }display: grid; grid-template-columns: 1fr 2fr 1fr; gap: 20px;
grid-template-columns: repeat(3, 1fr); grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); grid-template-columns: fit-content(300px) 1fr;
grid-template-areas:
'header header'
'sidebar main'
'footer footer';
.header { grid-area: header; }.parent { display: grid; grid-template-columns: repeat(3, 1fr); }
.child {
grid-column: span 3;
display: grid;
grid-template-columns: subgrid;
}.wide { grid-column: span 2; }
.tall { grid-row: span 3; }
.hero { grid-column: 1 / -1; }
.item { grid-column: 2 / 4; grid-row: 1 / 3; }place-items: center; place-self: end;
position: static | relative | absolute | fixed | sticky;
.parent { position: relative; }
.badge { position: absolute; top: 8px; right: 8px; }
.navbar { position: fixed; top: 0; left: 0; right: 0; z-index: 100; }
.header { position: sticky; top: 0; z-index: 10; }visibility: hidden; /* hidden, keeps space, not interactive */ opacity: 0; /* invisible, keeps space, still interactive */ display: none; /* hidden, no space, not interactive */
transform: translateX(20px); transform: scale(1.05) rotate(3deg); transform: translate(-50%, -50%); transform: skewX(15deg);
@media (max-width: 768px) { }
@media (prefers-color-scheme: dark) { }
@media (prefers-reduced-motion: reduce) { }cursor: default | pointer | text | move
| grab | grabbing | crosshair
| not-allowed | wait | zoom-in | none;Hover each box to see cursor change
pointer-events: none; user-select: none; user-select: all;
transition: all .3s ease; transition: color .2s ease, transform .3s cubic-bezier(.4,0,.2,1);
@keyframes fadeIn {
from { opacity: 0; transform: translateY(12px); }
to { opacity: 1; transform: translateY(0); }
}
.hero { animation: fadeIn .4s ease both; }@keyframes spin { to { transform: rotate(360deg); } }
.spinner {
width: 24px; height: 24px;
border: 3px solid rgba(0,0,0,.1);
border-top-color: #7c6dff;
border-radius: 50%;
animation: spin .8s linear infinite;
}@keyframes glow {
0%, 100% { box-shadow: 0 0 4px #7c6dff; }
50% { box-shadow: 0 0 20px #7c6dff, 0 0 40px #ec4899; }
}
.badge { animation: glow 2s ease-in-out infinite; }.spinner { animation: spin 1s linear infinite; }
.spinner.paused { animation-play-state: paused; }.animating { will-change: transform, opacity; }
.done { will-change: auto; }@media (prefers-reduced-motion: reduce) {
*, *::before, *::after {
animation-duration: .01ms !important;
animation-iteration-count: 1 !important;
transition-duration: .01ms !important;
}
}animation-fill-mode: none | forwards | backwards | both;
:root {
--color-primary: #7c6dff;
--spacing-md: 1rem;
--radius: 8px;
}
.btn {
background: var(--color-primary);
padding: var(--spacing-md);
border-radius: var(--radius);
}color: var(--brand-color, #7c6dff);
const root = document.documentElement;
root.style.setProperty('--color-primary', '#ff6b6b');
root.style.removeProperty('--color-primary');@property --hue {
syntax: '<number>';
inherits: false;
initial-value: 248;
}
.el { background: hsl(var(--hue), 80%, 60%); transition: --hue .3s; }
.el:hover { --hue: 330; }width: calc(100% - 2rem); font-size: clamp(1rem, 2.5vw, 1.5rem); width: min(600px, 100%); padding: max(1rem, 3vw);
width: round(nearest, 15.3px, 10px); margin: mod(18px, 5px); padding: rem(18px, 5px);
/* sin, cos, tan, asin, acos, atan, atan2 */ transform: rotate(calc(sin(45deg) * 1turn)); /* pow, sqrt, log, exp */ font-size: calc(pow(1.25, 3) * 1rem);
padding-top: env(safe-area-inset-top); padding-bottom: env(safe-area-inset-bottom); padding-left: env(safe-area-inset-left); padding-right: env(safe-area-inset-right);
| Unit | Relative to | Best used for |
|---|---|---|
| Absolute | ||
| px | Device pixel | Borders, shadows, fixed UI chrome |
| pt | 1/72 of an inch | Print stylesheets |
| Font-relative | ||
| em | Current element's font-size | Padding, margin relative to text size |
| rem | Root element's font-size | Font sizes, global spacing (preferred) |
| ch | Width of "0" character | Prose width (e.g. max-width: 65ch) |
| Viewport | ||
| vw | 1% of viewport width | Full-width sections, fluid typography |
| vh | 1% of viewport height | Heroes (with caveats on mobile) |
| dvh | Dynamic viewport height | Mobile full-height (accounts for URL bar) |
| svh | Small viewport height | Conservative mobile (URL bar visible) |
| lvh | Large viewport height | Optimistic mobile (URL bar hidden) |
| Grid / Flex | ||
| fr | Fraction of grid space | Grid column/row distribution |
| Percentage | ||
| % | Parent element | Fluid widths, heights, transforms |
html { font-size: 100%; }
h1 { font-size: 2rem; }
p { font-size: 1rem; }.hero { min-height: 100dvh; }.prose { max-width: 65ch; line-height: 1.7; }@media (prefers-reduced-motion: no-preference) {
html { scroll-behavior: smooth; }
}
html { scroll-padding-top: 80px; }
.section { scroll-margin-top: 80px; }.modal { overscroll-behavior: contain; }
body { overscroll-behavior-y: none; }.carousel { display: flex; overflow-x: auto; scroll-snap-type: x mandatory; gap: 16px; }
.slide { flex-shrink: 0; width: 300px; scroll-snap-align: start; scroll-snap-stop: always; }Scroll to snap to each item
.page { height: 100vh; overflow-y: scroll; scroll-snap-type: y mandatory; }
.section { height: 100vh; scroll-snap-align: start; }scrollbar-width: thin; scrollbar-color: #7c6dff transparent;
Line 2
Line 3
Line 4
Line 5
Line 6
Line 7
.custom::-webkit-scrollbar { width: 6px; }
.custom::-webkit-scrollbar-track { background: transparent; }
.custom::-webkit-scrollbar-thumb { background: #7c6dff; border-radius: 100px; }.hide-scroll { scrollbar-width: none; -ms-overflow-style: none; }
.hide-scroll::-webkit-scrollbar { display: none; }clip-path: circle(50%); clip-path: ellipse(60% 40% at 50% 50%); clip-path: polygon(50% 0%, 0% 100%, 100% 100%); clip-path: inset(10px 20px round 8px);
.reveal { clip-path: inset(0 100% 0 0); transition: clip-path .6s ease; }
.reveal.visible { clip-path: inset(0 0% 0 0); }.fade-bottom {
mask-image: linear-gradient(to bottom, black 60%, transparent);
-webkit-mask-image: linear-gradient(to bottom, black 60%, transparent);
}.spotlight {
mask-image: radial-gradient(circle at 50% 50%, black 30%, transparent 70%);
-webkit-mask-image: radial-gradient(circle at 50% 50%, black 30%, transparent 70%);
}
.shaped { mask-image: url('mask.svg'); mask-size: cover; mask-repeat: no-repeat; }mix-blend-mode: multiply | screen | overlay | difference | color-dodge | luminosity;
.card { isolation: isolate; }
.card .overlay { mix-blend-mode: multiply; }img {
width: 100%; height: 200px;
object-fit: cover;
object-fit: contain;
object-position: center top;
}.video { aspect-ratio: 16 / 9; width: 100%; }
.square { aspect-ratio: 1; }
.photo { aspect-ratio: 4 / 3; }:root { accent-color: #7c6dff; }
input[type="range"] { accent-color: #10b981; }input { caret-color: #7c6dff; }input, select, button { appearance: none; -webkit-appearance: none; }textarea { resize: vertical; }
textarea { resize: none; }
.panel { resize: both; overflow: auto; }touch-action: manipulation; touch-action: pan-y; touch-action: none;
a, button { -webkit-tap-highlight-color: transparent; }gap: 16px; gap: 8px 24px; row-gap: 8px; column-gap: 24px;
.news { columns: 3; column-gap: 2rem; }
.news { columns: 200px; }
column-rule: 1px solid #ccc;
.headline { column-span: all; }
.item { break-inside: avoid; }img { float: left; margin: 0 1rem 1rem 0; }
.next { clear: both; }
.container::after { content: ''; display: block; clear: both; }.avatar {
float: left;
shape-outside: circle(50%);
clip-path: circle(50%);
width: 150px; height: 150px;
margin: 0 1rem 0 0;
}
shape-outside: polygon(0 0, 100% 0, 50% 100%);
shape-outside: url('cutout.png');
shape-margin: 1rem;margin-left -> margin-inline-start margin-right -> margin-inline-end margin-top -> margin-block-start margin-bottom -> margin-block-end width -> inline-size height -> block-size border-top -> border-block-start border-left -> border-inline-start
margin-inline: auto; margin-block: 1.5rem; padding-inline: 1rem 2rem; inset: 0; inset-inline: 0; inset-block: 0;
.wrapper { container-type: inline-size; container-name: card; }
@container card (min-width: 400px) {
.card { flex-direction: row; }
}.card::before { content: ''; }
.badge::before { content: 'New'; }
a::after { content: ' (' attr(href) ')'; }
.q::before { content: open-quote; }
.q::after { content: close-quote; }
blockquote { quotes: '"' '"' "'" "'"; }body { counter-reset: section; }
h2::before {
counter-increment: section;
content: 'Section ' counter(section) ': ';
}.steps { counter-reset: step; }
.step { counter-increment: step; }
.step::before {
content: counter(step);
display: inline-flex;
width: 28px; height: 28px;
align-items: center; justify-content: center;
border-radius: 50%;
background: #7c6dff; color: #fff;
font-weight: 600; margin-right: .5rem;
}@counter-style thumbs {
system: cyclic;
symbols: '👍' '✅' '🚀';
suffix: ' ';
}
ul { list-style: thumbs; }.ball {
offset-path: path('M 0 0 C 100 0, 200 100, 300 0');
offset-distance: 0%;
animation: move 2s linear infinite;
}
@keyframes move { to { offset-distance: 100%; } }.dot {
offset-path: circle(80px at center);
offset-distance: 0%;
animation: orbit 3s linear infinite;
}
@keyframes orbit { to { offset-distance: 100%; } }@layer base, components, utilities;
@layer base { body { font-family: sans-serif; } }
@layer utilities { .mt-4 { margin-top: 1rem; } }@supports (display: grid) { .layout { display: grid; } }
@supports not (backdrop-filter: blur()) {
.glass { background: rgba(0,0,0,.7); }
}
@supports selector(:has(a)) { .nav:has(.active) { background: #f5f5f5; } }@scope (.card) {
p { color: #333; }
h2 { font-size: 1.25rem; }
}@property --angle {
syntax: '<angle>';
inherits: false;
initial-value: 0deg;
}
.spinner {
background: conic-gradient(#7c6dff var(--angle), transparent 0);
animation: rotate 1s linear infinite;
}
@keyframes rotate { to { --angle: 360deg; } }.progress-bar {
position: fixed; top: 0; left: 0; right: 0; height: 4px;
background: #7c6dff;
transform-origin: left;
animation: grow linear;
animation-timeline: scroll(root);
}
@keyframes grow { from { transform: scaleX(0); } to { transform: scaleX(1); } }.card {
animation: fadeSlide linear both;
animation-timeline: view();
animation-range: entry 0% entry 30%;
}
@keyframes fadeSlide {
from { opacity: 0; transform: translateY(20px); }
to { opacity: 1; transform: translateY(0); }
}@page { size: A4 portrait; margin: 2cm; }
@page :first { margin-top: 4cm; }
@page :left { margin-left: 3cm; }
@page :right { margin-right: 3cm; }@media print {
nav, .sidebar, .ads, button { display: none; }
body { font-size: 12pt; color: #000; background: #fff; }
a::after { content: ' (' attr(href) ')'; font-size: 10pt; }
}h1 { break-before: page; }
.chapter { break-after: page; }figure, table, pre, blockquote { break-inside: avoid; }
tr { break-inside: avoid; }
p { orphans: 3; widows: 3; }A CSS cheat sheet is a quick-reference tool for developers who need fast access to properties, selectors, and rules without digging through documentation.
CSS has grown considerably. What started as a simple styling language now covers layout systems, animations, custom properties, math functions, and scroll-driven effects. Keeping track of it all is genuinely hard.
This reference covers the full spectrum of modern CSS, organized into tabs so you can jump directly to what you need:
-
Selectors - type, class, ID, combinators, pseudo-classes, pseudo-elements, and attribute selectors
-
Box Model - the modern CSS reset, margin, padding, border, outline, box-shadow, overflow, and inset
-
Typography - font properties, OpenType features,
font-variant-numeric,text-wrap: balance, writing modes, and truncation patterns -
Colors & Backgrounds - every color format, gradients (linear, radial, conic), filters, glassmorphism,
color-mix(), andlight-dark() -
Flexbox & Grid - container and item properties, subgrid,
fit-content(), named areas, and alignment shorthands -
Positioning - all position values, transforms, display, visibility, cursor,
pointer-events, anduser-select -
Animations - transitions,
@keyframes,animation-play-state,will-change, andprefers-reduced-motion -
Variables & Functions - custom properties,
@property,calc(),clamp(),env(), trig functions, andround() -
Units - every unit from
pxtodvhtofr, with guidance on when to use each -
Scroll - smooth scrolling, scroll snap,
overscroll-behavior, and scrollbar styling -
Visual Effects -
clip-path,mask-image,mix-blend-mode,isolation,object-fit, andaspect-ratio -
Interaction & UI -
accent-color,appearance,resize,touch-action, and mobile tap handling -
Layout+ - multi-column, float,
shape-outside, logical properties, and container queries -
Generated Content -
content, CSS counters,@counter-style, and motion path animation -
At-Rules -
@layer,@supports,@scope,@property, and scroll-driven animations -
Print -
@page, print media queries, page breaks, widows, and orphans
Every snippet is copy-ready. Most include live previews so you can see the effect before using it. The search bar (press / to focus) filters across all tabs instantly.
Built for web designers who already know CSS and need a fast lookup, not a tutorial.
What is CSS
CSS is a stylesheet language that controls how HTML elements look on a page - layout, color, spacing, typography, and more.
It separates content from presentation.
Without CSS, every webpage would be unstyled plain text. With it, you can build polished, responsive interfaces across any screen size.
CSS Syntax
CSS follows a straightforward pattern: a selector targets an element, and a declaration block defines its style.
selector {
property: value;
}
Every declaration ends with a semicolon. Miss one, and the rule after it may silently break.
CSS Rule Structure
A CSS rule has two parts: the selector and the declaration block.
The declaration block holds one or more property: value pairs wrapped in curly braces.
Whitespace is ignored. You can write a rule on one line or spread it across ten - the browser doesn't care.
CSS Selectors
Selectors define what gets styled. Getting them right is most of the work.
Element Selectors
Targets all instances of an HTML tag.
p { color: #333; } - applies to every <p> on the page.
Broad. Useful for resets and base styles.
Class Selectors
Prefixed with a dot. .card { padding: 1rem; }
Reusable across multiple elements. The go-to for component-level styling.
ID Selectors
Prefixed with #. High specificity - they override most other rules.
Use sparingly. IDs are meant to be unique per page, which makes them tricky to reuse.
Attribute Selectors
Target elements based on the presence or value of an attribute.
input[type="email"] - only matches email inputs.
Useful for styling form fields, links with specific href patterns, or custom data attributes.
Pseudo-class Selectors
Style elements based on state or position.
:hover, :focus, :nth-child(2), :not(.active) - these don't target the element itself, but a condition it's in.
Essential for interactive UI and dynamic states.
Pseudo-element Selectors
Target a specific part of an element rather than the element itself.
::before and ::after inject content. ::placeholder styles input hints. ::selection controls highlighted text color.
Two colons (::) is the modern syntax. One colon still works in most browsers for legacy reasons.
CSS Combinators
Combinators define relationships between selectors.
-
div p- descendant (any<p>inside a<div>) -
div > p- direct child only -
h2 + p- adjacent sibling (immediately after) -
h2 ~ p- general sibling (any<p>after theh2)
Combinators are powerful for contextual styling without adding extra classes to your markup.
CSS Box Model
Every element on the page is a rectangular box.
The box model describes how that box is calculated: content area, padding, border, and margin - stacked outward from the inside.
Understanding this model is what separates developers who fight CSS from those who don't.
Content Area
The innermost layer. Width and height properties apply here by default.
Set width: 300px and that's the content width - not the total visible width of the box.
Padding
Space between the content and the border. Transparent, takes the element's background color.
padding: 1rem adds space on all sides. Use padding-top, padding-left, etc. for individual sides.
Border
Sits between padding and margin. Adds to the visible size of the element unless box-sizing: border-box is applied.
border: 1px solid #ddd is probably the most written CSS line in history.
Margin
Space outside the border. Transparent, no background color.
Margins between two block elements collapse - the larger margin wins, not the sum of both. This trips up nearly everyone at some point.
Box Sizing
By default, box-sizing is content-box.
Switch to **border-box** and the element's total width includes padding and border - much more predictable.
*, *::before, *::after {
box-sizing: border-box;
}
Put this at the top of every stylesheet. Always.
CSS Units
CSS has two categories of units: absolute and relative.
Absolute units have a fixed size. Relative units scale based on something else - parent element, root font size, viewport dimensions.
Absolute Units
Fixed regardless of context.
px
Pixels. The most common absolute unit. font-size: 16px, border: 1px solid.
Device pixels and CSS pixels aren't always 1:1 on high-density screens, but px remains the default for fine-grained control.
pt
Points. Used in print stylesheets. 1pt = 1/72 of an inch. Rarely used for screens.
cm
Centimeters. Essentially only useful for print layouts. Avoid on screen.
Relative Units
Scale dynamically. Use these for responsive design.
em
Relative to the font-size of the parent element.
padding: 1.5em on a button means 1.5x whatever font size the parent has. Can compound unexpectedly in deeply nested elements.
rem
Relative to the root (<html>) font size. Consistent across nesting.
Most developers default to rem for font sizes and spacing. Much more predictable than em.
%
Percentage of the parent element's size. width: 50% means half the parent's width.
Common for fluid layouts and responsive containers.
vw and vh
vw = 1% of the viewport width. vh = 1% of the viewport height.
height: 100vh makes a section fill the full screen. Used heavily in hero sections and full-bleed layouts.
ch and ex
ch = width of the 0 character in the current font. Useful for setting max-width on text containers - max-width: 65ch is a solid readable line length.
ex = height of the x character. Rarely used in practice.
CSS Colors
CSS supports multiple color formats. They all produce the same output - pick whatever fits your workflow.
Color Values
Named Colors
Plain English. red, blue, cornflowerblue, rebeccapurple.
147 named colors in CSS. Great for quick prototyping, not for production design systems.
HEX Values
Six-character hex codes. #ff6b6b, #1a1a2e.
Add two more characters for alpha transparency: #ff6b6bcc.
The most widely used format in design files and design tokens.
RGB and RGBA
rgb(255, 107, 107) - red, green, blue, each 0–255.
rgba(255, 107, 107, 0.5) adds opacity. The alpha channel goes from 0 (transparent) to 1 (fully opaque).
HSL and HSLA
hsl(0, 100%, 65%) - hue (0–360°), saturation (%), lightness (%).
HSL is the most intuitive format for humans. Adjusting lightness alone gives you tints and shades of the same color. Much easier to reason about than RGB.
currentColor
A special keyword that inherits the element's color value.
border: 1px solid currentColor - the border will always match the text color. Useful for icons and decorative elements that should adapt automatically.
Opacity Property
opacity: 0.5 makes the entire element 50% transparent - including children.
Different from RGBA, which only affects the background or color. If you only want a semi-transparent background, use rgba() or hsla() on the background property, not opacity.
CSS Typography
Typography properties split into two groups: font properties (what the text is) and text properties (how it behaves).
Font Properties
font-family
Defines the typeface. Always include a fallback stack.
font-family: 'Inter', Arial, sans-serif - browser uses the first available font.
font-size
Sets text size. Use rem for accessibility - it respects user browser preferences, unlike px.
font-weight
Controls thickness. 400 = normal, 700 = bold. Named values (bold, light) also work, but numeric values are more precise.
font-style
normal, italic, or oblique. Mostly used to set or reset italic styling.
font-variant
font-variant: small-caps renders lowercase letters as smaller uppercase letters. Niche use case - mainly for legal text or formal typographic layouts.
Text Properties
text-align
left, right, center, justify. Applies to block-level elements.
justify looks clean in print. On screens with short line lengths, it creates awkward gaps.
text-decoration
Underlines, overlines, strikethroughs. text-decoration: none is used constantly to remove default link underlines.
text-transform
uppercase, lowercase, capitalize. Transforms display without changing the HTML.
Use CSS for visual casing, not markup - keeps content accessible to screen readers.
letter-spacing
Adjusts space between characters. Slightly positive values improve readability on uppercase headings.
Negative values tighten text. Useful at large display sizes; risky at body size.
line-height
Controls vertical spacing between lines of text. 1.5 to 1.7 is the readable range for body copy.
No unit needed - line-height: 1.6 is relative to the element's own font size.
word-spacing
Adds or removes space between words. Rarely needed - browsers handle word spacing well by default.
Web Fonts
Load custom fonts via @font-face or a service like Google Fonts.
@font-face {
font-family: 'MyFont';
src: url('myfont.woff2') format('woff2');
}
Always serve woff2 first - it's the most compressed format with the widest modern browser support.
CSS Backgrounds
Background Color
background-color: #f5f5f5 - sets a solid fill.
Accepts any CSS color format: HEX, RGB, HSL, named colors.
Background Image
background-image: url('image.jpg') - sets an image behind the element's content.
Combine with background-size, background-position, and background-repeat to control how it renders.
Background Size
cover
Scales the image to cover the entire element. Crops if needed. The standard for hero sections.
contain
Scales the image to fit inside the element without cropping. Shows whitespace if aspect ratios don't match.
auto
Renders the image at its natural size. Fine for small repeating patterns.
Background Position
Controls where the background image starts. center center, top right, percentage values, or pixel offsets.
background-position: center is the default for full-bleed images.
Background Repeat
no-repeat stops the image from tiling. repeat-x or repeat-y tiles in one direction.
Default is repeat - set no-repeat on any image you don't want tiled.
Background Attachment
fixed keeps the background stationary while the page scrolls - creates a parallax-like effect.
scroll (default) moves with the element. local scrolls with the element's own content.
Background Shorthand
background: #1a1a2e url('texture.jpg') no-repeat center / cover;
Order: color, image, repeat, position / size. Readable once you know the pattern.
CSS Layout
Display Property
Display is the most important layout property in CSS. It defines how an element participates in the document flow.
block
Takes up the full width available. Stacks vertically. div, p, h1–h6 are block by default.
inline
Only as wide as its content. Sits in line with text. Ignores width/height settings.
inline-block
Inline flow, but respects width and height. Useful for buttons and tags that should sit in text flow but have defined dimensions.
none
Removes the element from the layout entirely. Takes up no space. Different from visibility: hidden, which hides but preserves space.
Position Property
Controls how an element is placed relative to its normal position or a container.
static
Default. Follows normal document flow. top, left, right, bottom have no effect.
relative
Stays in normal flow but can be nudged with offset properties. Also creates a new stacking context for absolute children.
absolute
Removed from document flow. Positioned relative to the nearest non-static ancestor. If none exists, it positions against the viewport.
fixed
Removed from document flow. Positioned relative to the viewport. Stays put on scroll. Used for sticky headers and floating buttons.
sticky
Hybrid of relative and fixed. Behaves as relative until a scroll threshold is reached, then sticks. Requires a defined top, bottom, left, or right value.
Float and Clear
float: left or float: right pulls an element to one side, letting content wrap around it.
clear: both stops an element from sitting beside floated elements. Floats are mostly legacy - use Flexbox or Grid for modern layouts.
Overflow
Controls what happens when content is larger than its container.
overflow: hidden clips content. overflow: scroll always shows scrollbars. overflow: auto only shows scrollbars when needed - the most practical default.
CSS Flexbox
Flexbox is a one-dimensional layout model - it handles either a row or a column, not both.
Apply display: flex to a container. Its direct children become flex items.
Flex Container Properties
display: flex
Activates the flex formatting context. All direct children become flex items automatically.
flex-direction
row (default), column, row-reverse, column-reverse. Defines the main axis.
flex-wrap
nowrap by default - items shrink to fit on one line. wrap lets items spill onto new lines.
justify-content
Aligns items along the main axis. flex-start, flex-end, center, space-between, space-around, space-evenly.
align-items
Aligns items along the cross axis. stretch (default), center, flex-start, flex-end, baseline.
align-content
Works like justify-content but for the cross axis - only relevant when flex-wrap: wrap is set and there are multiple rows.
Flex Item Properties
flex-grow
How much extra space an item takes relative to siblings. flex-grow: 1 shares space equally. flex-grow: 2 takes double the share.
flex-shrink
How much an item shrinks when space is tight. 1 by default. Set to 0 to prevent shrinking.
flex-basis
The starting size before grow/shrink is applied. auto uses the item's natural size. Can be any length value.
order
Changes visual order without touching the HTML. order: -1 moves an item to the front.
align-self
Overrides align-items for a single flex item. Same values: auto, flex-start, flex-end, center, stretch, baseline.
CSS Grid
CSS Grid is a two-dimensional layout system - rows and columns simultaneously.
Works alongside Flexbox. Grid handles macro layout; Flexbox handles component internals.
Grid Container Properties
grid-template-columns
Defines column sizes. grid-template-columns: 1fr 2fr 1fr creates three columns with proportional widths.
repeat(3, 1fr) is shorthand for three equal columns.
grid-template-rows
Same as columns, but for rows. grid-template-rows: auto 1fr auto - common for header/main/footer layouts.
grid-template-areas
Names regions of the grid for readable layout definitions.
grid-template-areas:
"header header"
"sidebar main"
"footer footer";
gap (column-gap, row-gap)
Sets spacing between grid tracks. gap: 1rem applies to both rows and columns.
column-gap and row-gap control them separately.
justify-items
Aligns grid items horizontally within their cells. start, end, center, stretch (default).
align-items
Aligns grid items vertically within their cells. Same values as justify-items.
Grid Item Properties
grid-column
Controls how many columns an item spans. grid-column: 1 / 3 runs from column line 1 to line 3.
grid-column: span 2 is the shorthand.
grid-row
Same logic as grid-column, but for rows. grid-row: 2 / 4 spans two row tracks.
grid-area
Assigns an item to a named area defined in grid-template-areas. grid-area: header.
Also shorthand for grid-row-start / grid-column-start / grid-row-end / grid-column-end.
Implicit vs Explicit Grid
Explicit grid: tracks you define with grid-template-columns and grid-template-rows.
Implicit grid: tracks the browser creates automatically when items overflow the defined grid. Control their size with grid-auto-rows and grid-auto-columns.
CSS Transitions
Transitions animate property changes from one state to another.
They trigger on state changes: :hover, :focus, class additions via JavaScript.
transition-property
Specifies which CSS property to animate. transition-property: background-color - only that property transitions.
all animates every changing property. Convenient but can cause unintended animations.
transition-duration
How long the animation takes. 0.3s is the sweet spot for UI interactions - fast enough to feel instant, slow enough to be visible.
transition-timing-function
Controls the acceleration curve.
ease
Starts slow, accelerates, ends slow. The default. Feels natural for most UI transitions.
linear
Constant speed. Good for progress bars, loaders. Feels mechanical for UI elements.
ease-in
Starts slow, ends fast. Feels like something being thrown. Good for exit animations.
ease-out
Starts fast, ends slow. Feels like something landing. Good for enter animations.
cubic-bezier
Full control over the curve. cubic-bezier(0.68, -0.55, 0.27, 1.55) creates a springy overshoot effect.
transition-delay
Waits before starting. transition-delay: 0.1s creates staggered effects when combined with multiple elements.
Transition Shorthand
transition: background-color 0.3s ease 0s;
Order: property, duration, timing-function, delay.
CSS Animations
Animations differ from transitions: they don't need a trigger state and can loop, reverse, and pause.
@keyframes Rule
Defines the animation sequence.
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
Use percentage values (0%, 50%, 100%) for multi-step animations.
animation-name
References the @keyframes name. animation-name: fadeIn.
animation-duration
How long one cycle takes. Required - defaults to 0s, which plays nothing.
animation-timing-function
Same values as transition-timing-function. Applies to each keyframe interval, not the full animation.
animation-delay
Delays the start. Negative values start the animation partway through - useful for staggering elements that share the same keyframe.
animation-iteration-count
1 (default), any positive number, or infinite. infinite is common for loaders and ambient effects.
animation-direction
normal (default), reverse, alternate, alternate-reverse. alternate ping-pongs between from and to states.
animation-fill-mode
What styles apply before and after the animation.
forwards keeps the final keyframe state after the animation ends. backwards applies the first keyframe during the delay period. both covers both scenarios.
Animation Shorthand
animation: fadeIn 0.5s ease forwards;
CSS Transforms
Transforms modify an element's visual appearance without affecting document flow.
Other elements don't reflow when you apply a transform. The original space is preserved.
2D Transform Functions
translate()
Moves an element. transform: translate(50px, 20px) shifts right 50px, down 20px.
translateX() and translateY() move along a single axis.
scale()
Resizes. transform: scale(1.5) makes the element 150% its original size.
scale(1) is the default. Values below 1 shrink; above 1 enlarge.
rotate()
Rotates by a given angle. transform: rotate(45deg). Positive values rotate clockwise.
skew()
Tilts along the X or Y axis. transform: skew(10deg, 5deg). Creates a slanted, italic-like effect on non-text elements.
3D Transform Functions
rotateX()
Rotates around the horizontal axis - top or bottom tilts toward or away from the viewer.
Needs perspective on the parent to look realistic.
rotateY()
Rotates around the vertical axis. Used for card flip effects.
perspective()
Applied via transform: perspective(800px) rotateY(30deg) or as a property on the parent. Lower values create more dramatic depth.
transform-origin
Sets the pivot point for transforms. Default is 50% 50% (center).
transform-origin: top left rotates or scales from the top-left corner.
CSS Variables
CSS custom properties are reusable values defined once and referenced throughout the stylesheet.
:root {
--color-primary: #2563eb;
--spacing-base: 1rem;
}
Declaring Custom Properties
Declare on :root for global scope. Name must start with --.
Case-sensitive: --Color and --color are different variables.
Using CSS Variables
Reference with var(). color: var(--color-primary).
Change one variable and every element using it updates instantly. Perfect for theming.
Variable Scope
Variables are scoped to the element they're declared on and its descendants.
Declare inside a component class to limit scope. Declare on :root to make it global.
Fallback Values
var(--color-accent, #ff6b6b) - uses #ff6b6b if --color-accent isn't defined.
Useful during development or for progressive enhancement in component libraries.
CSS Media Queries
Media queries apply styles conditionally based on device or viewport characteristics.
Core tool for responsive design. Most used feature alongside Flexbox and Grid.
Syntax and Structure
@media (max-width: 768px) {
.container { padding: 1rem; }
}
The rule block applies only when the condition is true.
Breakpoints
Mobile Breakpoints
Typically max-width: 480px or max-width: 640px.
Mobile-first: write base styles for small screens, then override with min-width queries for larger ones.
Tablet Breakpoints
768px to 1024px covers most tablet viewport ranges.
Desktop Breakpoints
min-width: 1024px or min-width: 1280px for standard desktop. min-width: 1440px for wide-screen layouts.
No single set of breakpoints is universally correct - design around your actual content, not arbitrary device sizes.
Media Features
width and height
min-width, max-width, min-height, max-height are the most used features.
Modern CSS prefers range syntax: @media (width >= 768px).
orientation
portrait or landscape. @media (orientation: landscape) targets devices held sideways.
resolution
min-resolution: 2dppx targets high-density (Retina) screens. Useful for serving higher-quality background images.
Logical Operators in Media Queries
and
Combines conditions. @media (min-width: 768px) and (max-width: 1024px) - only applies in that range.
not
Inverts a condition. @media not (prefers-color-scheme: dark) applies to non-dark-mode contexts.
only
Hides queries from older browsers. @media only screen and (...) - legacy syntax, rarely needed now.
CSS Specificity
When two rules target the same element, specificity determines which one wins.
Understanding specificity stops you from writing increasingly aggressive overrides.
Specificity Calculation
Each selector type has a weight:
-
Inline styles: 1,0,0,0
-
ID selectors: 0,1,0,0
-
Class, attribute, pseudo-class: 0,0,1,0
-
Element, pseudo-element: 0,0,0,1
Compare columns left to right. Higher column wins, regardless of the number in lower columns.
Specificity Hierarchy
Inline styles beat IDs. IDs beat classes. Classes beat element selectors.
A single class beats any number of element selectors.
!important Rule
Overrides all specificity. color: red !important wins over everything.
Use it as a last resort. Overusing !important makes stylesheets nearly impossible to maintain.
Inheritance in CSS
Some properties inherit from parent to child by default - color, font-size, font-family.
Others don't - border, margin, padding. Use inherit to force inheritance, or initial to reset to the browser default.
CSS Pseudo-classes
Pseudo-classes apply styles based on element state, position, or relationship - without adding classes to the HTML.
Structural Pseudo-classes
:first-child
Targets an element only if it's the first child of its parent.
li:first-child - the first list item only.
:last-child
Same logic, last child. li:last-child { border-bottom: none } - removes the last divider in a list.
:nth-child()
Accepts numbers, keywords, or formulas. :nth-child(odd), :nth-child(3n+1).
Useful for zebra-striping tables or controlling grid item colors.
:not()
Excludes elements from a rule. a:not(.active) targets all links except those with .active.
Cleaner than writing separate rules for exclusions.
State Pseudo-classes
:hover
Activates when the pointer is over the element. The most commonly used pseudo-class.
Don't rely on it for touch interfaces - hover doesn't exist on mobile.
:focus
Applies when an element receives keyboard or click focus. Critical for keyboard accessibility.
Never remove focus styles without replacing them with a visible alternative.
:active
Applies while the element is being clicked. Usually lasts milliseconds.
Useful for button press feedback.
:visited
Applies to links that have been visited. Restricted to color properties only for privacy reasons.
CSS Pseudo-elements
Pseudo-elements target a specific sub-part of an element - not the element itself, not a child.
Double colon (::) is the correct modern syntax.
::before and ::after
Inserts generated content before or after an element's content. Must have content: '' to render.
Widely used for decorative shapes, icons, overlays, and clearfix hacks. No extra HTML required.
::placeholder
Styles the placeholder text in form inputs.
input::placeholder { color: #aaa; font-style: italic; }
::selection
Styles text highlighted by the user. Only color, background-color, and text-shadow are supported.
::selection { background-color: #2563eb; color: white; }
::first-line and ::first-letter
::first-line targets the first rendered line of a block element - useful for drop-cap typographic effects alongside ::first-letter.
::first-letter enlarges or styles the first character of a paragraph.
CSS Functions
CSS functions are called directly in property values. No JavaScript needed.
calc()
Mixes units. width: calc(100% - 2rem) subtracts a fixed amount from a fluid width.
Spaces around the operator are required: calc(100% - 2rem) works; calc(100%-2rem) doesn't.
clamp()
clamp(min, preferred, max) - fluid scaling within a range.
font-size: clamp(1rem, 2.5vw, 2rem) scales with viewport width but never goes below 1rem or above 2rem. Essential for fluid typography.
min() and max()
min(50%, 400px) uses whichever value is smaller. max(200px, 30%) uses whichever is larger.
Useful for responsive sizing without media queries.
var()
References a CSS custom property. Covered in CSS Variables above.
rgb() and hsl()
Color functions. Both support an optional alpha channel in modern syntax: rgb(255 107 107 / 0.5).
The slash syntax is newer - check browser support if targeting legacy environments.
url()
References an external resource. background-image: url('pattern.svg'), @font-face src: url('font.woff2').
Relative paths resolve from the stylesheet's location, not the HTML file.
linear-gradient() and radial-gradient()
linear-gradient(135deg, #1a1a2e, #16213e) - diagonal gradient between two colors.
radial-gradient(circle, #fff, #000) - radial spread from center. Both accept multiple color stops.
CSS at-rules
At-rules are instructions to the CSS engine that start with @.
@import
Loads an external stylesheet. @import url('reset.css').
Must be at the top of the file. Blocks rendering - use <link> tags in HTML for better performance.
@media
Conditional styles based on media features. Covered in Media Queries above.
@keyframes
Defines animation sequences. Covered in CSS Animations above.
@font-face
Loads custom fonts from local or remote files. Covered in Web Fonts above.
@supports
Applies styles only if the browser supports a given property.
@supports (display: grid) {
.layout { display: grid; }
}
Safe fallback mechanism for using modern CSS without breaking older browsers.
@layer
Defines cascade layers - a way to organize styles by explicit priority rather than relying on source order.
@layer base, components, utilities;
Later layers win over earlier ones. Gives you deliberate control over the cascade without specificity battles.
CSS Cascade and Inheritance
The cascade is the algorithm CSS uses to decide which rule applies when multiple rules compete.
It's not random. The order is predictable once you understand the factors.
How the Cascade Works
The cascade considers four factors, in order: origin and importance, context (shadow DOM), specificity, order of appearance.
Same specificity? The last declared rule wins.
Origin Types
Author Styles
Styles written by the developer. Highest priority among normal rules.
User Styles
Styles set by the browser user (custom stylesheets, accessibility tools). Override author styles only when marked !important.
Browser (User-Agent) Styles
Default styles built into every browser. Why buttons look like buttons and links are blue before you write a single line of CSS.
A CSS reset or normalize stylesheet neutralizes these defaults.
Inherited vs Non-inherited Properties
Inherited: color, font-*, line-height, visibility, cursor. Children get the parent's value automatically.
Non-inherited: margin, padding, border, background, width, height. Must be explicitly set.
all Property
all: unset resets every property on an element to either inherit or initial. Useful for resetting third-party component styles inside a shadow DOM or isolated component.
CSS Overflow and Scrolling
overflow-x and overflow-y
Control overflow on each axis independently. overflow-x: hidden clips horizontal content without affecting vertical scrolling.
overflow: hidden on a parent also creates a new block formatting context - this is why it's used as a clearfix.
scroll-behavior
scroll-behavior: smooth enables smooth scrolling for anchor links and programmatic scroll calls.
Apply on :root or html for site-wide smooth scrolling.
overscroll-behavior
Controls what happens when scrolling reaches the edge of a container.
overscroll-behavior: contain stops scroll chaining - the parent won't scroll when the child reaches its limit.
Useful for modals, sidebars, and chat interfaces.
CSS Filters
Filters apply visual effects to elements using the GPU.
They work on any element, not just images. Apply to video, canvas, or entire sections.
blur()
filter: blur(4px) - softens the element. Used for frosted glass effects.
Combine with backdrop-filter: blur() to blur content behind an element.
brightness()
filter: brightness(0.8) darkens; values above 1 lighten. 0 is black.
contrast()
filter: contrast(1.2) increases contrast. 0 renders gray.
grayscale()
filter: grayscale(1) removes all color. grayscale(0.5) is half desaturated.
drop-shadow()
Similar to box-shadow but follows the actual shape of the element - including transparent PNGs.
filter: drop-shadow(2px 4px 8px rgba(0,0,0,0.3)).
backdrop-filter
Applies filter effects to the area behind the element, not the element itself.
backdrop-filter: blur(12px) brightness(0.8) creates a frosted glass panel. Requires a semi-transparent background on the element to be visible.
CSS clip-path and Masking
clip-path Values
Clips the visible area of an element to a defined shape.
clip-path: circle(50%) creates a circular mask. clip-path: polygon(0 0, 100% 0, 80% 100%, 0 100%) creates custom shapes.
Animatable - combine with transitions for shape-reveal effects.
mask-image
Uses an image or gradient as a mask. Transparent areas in the mask hide the element; opaque areas reveal it.
mask-image: linear-gradient(to bottom, black, transparent) fades an element toward the bottom.
mask-size and mask-position
Work exactly like background-size and background-position. mask-size: cover scales the mask to fill the element.
CSS Writing Modes and Logical Properties
writing-mode
Controls text flow direction. vertical-rl runs text top-to-bottom, right-to-left - used for CJK typography and creative vertical layouts.
horizontal-tb is the default for Latin scripts.
direction
ltr (left-to-right) or rtl (right-to-left). Relevant for Arabic, Hebrew, and other RTL languages.
Set on the <html> element, not in CSS alone - the dir attribute in HTML is preferred for proper text handling.
Logical vs Physical Properties
Physical properties: margin-left, padding-top, border-right. Tied to screen directions.
Logical properties adapt to writing mode and text direction. margin-inline-start replaces margin-left - it means "start of the inline axis," which is left in LTR and right in RTL.
Use logical properties for any interface that supports multiple languages or writing directions.
FAQ on CSS Cheat Sheets
What is a CSS cheat sheet used for?
A CSS cheat sheet is a quick reference card for CSS properties, selectors, and syntax.
It saves time by listing stylesheet syntax, shorthand properties, and values in one place - no need to search documentation for every rule you half-remember.
What are the most important CSS properties to know?
Start with the box model, display, position, flexbox, and grid.
Add color values, font properties, and media queries. Those cover 90% of real-world styling needs before you ever touch transitions or transforms.
What is the difference between margin and padding in CSS?
Padding is space inside the element, between content and border. Margin is space outside the border, between the element and its neighbors.
Margins collapse between block elements. Padding never does.
How does CSS specificity work?
Specificity decides which rule wins when two selectors target the same element.
Inline styles beat IDs, IDs beat class selectors, classes beat element selectors. Same specificity? The last rule in the stylesheet wins.
What is the CSS box model?
Every element is a rectangle: content area, padding, border, and margin stacked outward.
By default, width applies to the content area only. Set box-sizing: border-box so padding and border are included in the declared width.
What is the difference between Flexbox and CSS Grid?
Flexbox is one-dimensional - rows or columns, not both at once. CSS Grid is two-dimensional, handling rows and columns simultaneously.
Use Grid for page-level layout. Use Flexbox for component internals and aligning items within a single axis.
What are CSS variables and how do you use them?
CSS variables, also called custom properties, store reusable values declared with -- prefix.
Define them on :root for global scope: --color-primary: #2563eb. Reference anywhere with var(--color-primary). Changing one variable updates every element using it.
What is the difference between px, em, and rem in CSS?
px is a fixed absolute unit. em is relative to the parent element's font size - it compounds in nested elements.
rem is relative to the root font size only. More predictable than em. Preferred for font sizes and spacing in responsive layouts.
How do CSS media queries work?
Media queries apply CSS rules conditionally based on viewport size or device characteristics.
@media (min-width: 768px) activates styles only at that breakpoint and above. Write mobile-first: base styles for small screens, then layer wider breakpoints with min-width.
What is CSS cascade and why does it matter?
The cascade is the algorithm CSS uses to resolve conflicts between competing rules.
It weighs origin, specificity, and source order - in that sequence. Understanding it means fewer !important overrides and cleaner, more maintainable stylesheets.