Cheatsheet
CSS
Selectors
UniversalCopy
* {
box-sizing: border-box;
}iApplies a style to literally every element on the page. Often used to reset spacing before you start styling.TypeCopy
p {
color: #222;
}iApplies a style to every element of one HTML tag, like every paragraph.ClassCopy
.card {
padding: 1rem;
}iApplies a style to any element you've labeled with that class name. The same class can be reused on many elements.IDCopy
#header {
height: 60px;
}iApplies a style to one specific element — the one with that exact ID. Each ID should only be used once per page.AttributeCopy
input[type="text"] {
border: 1px solid #ccc;
}
a[href^="https"] { }
img[src$=".png"] { }
[class*="col-"] { }iTargets elements based on one of their HTML attributes, like an input's type or a link's web address. ^= means "starts with", $= means "ends with", *= means "contains".GroupingCopy
h1, h2, h3 {
font-weight: 600;
}iApplies the same style to several different selectors at once by listing them separated by commas.DescendantCopy
.card p {
margin: 0;
}iTargets an element only when it's nested inside another one, no matter how many levels deep.Direct childCopy
.list > li {
list-style: none;
}iTargets an element only when it sits directly inside another one, one level down — not deeper.General siblingCopy
h2 ~ p {
color: gray;
}iTargets an element that comes anywhere after another one, as long as they share the same parent.Adjacent siblingCopy
h2 + p {
margin-top: 0;
}iTargets an element only when it comes immediately after another specific one.Pseudo-classes
User actionCopy
a:hover { }
button:active { }
input:focus { }
input:focus-visible { }iStyles an element based on what a visitor is doing with it — hovering their mouse over it, clicking it, or having it focused.StructuralCopy
li:first-child { }
li:last-child { }
li:only-child { }
tr:nth-child(2n) { }
tr:nth-child(odd) { }
p:nth-of-type(2) { }iTargets an element based on its position in a list — the first one, the last one, or every other row, for example.Form stateCopy
input:checked { }
input:disabled { }
input:required { }
input:invalid { }
input:placeholder-shown { }iStyles a form field based on its current state, like whether a checkbox is ticked or a field still needs to be filled in.NegationCopy
button:not(.disabled) { }iStyles an element only when it does NOT match another selector.Matches-any (:is / :where)Copy
:is(h1, h2, h3) { color: #111; }
// :where() same as :is() but 0 specificity
:where(header, footer) a { color: blue; }iA shortcut for grouping several selectors that share the same surrounding context, instead of writing each one out in full.Relational (:has)Copy
a:has(> img) { }
figure:has(figcaption) { border: 1px solid; }
form:has(:invalid) { border-color: red; }iStyles an element based on what's INSIDE it — for example, giving a form a red border only if one of its fields is invalid.OtherCopy
:root { }
:target { }
:empty { }
:lang(en) { }i:root targets the very top of the page (handy for site-wide settings). :target matches whichever section a link on the page is currently pointing to. :empty matches elements with nothing inside them.Pseudo-elements
Before / AfterCopy
.tooltip::before {
content: "\2192";
}iInserts extra content right before or after an element's own content, without needing to add it to your HTML.First line / letterCopy
p::first-line { font-weight: bold; }
p::first-letter { font-size: 2em; }iStyles just the first line of a paragraph, or just its very first letter.SelectionCopy
::selection {
background: #ffe58a;
}iStyles the text a visitor highlights by dragging their mouse across it.PlaceholderCopy
input::placeholder {
color: #999;
}iStyles the greyed-out hint text shown inside an empty input box before someone starts typing.MarkerCopy
li::marker {
color: red;
}iStyles the bullet point or number sitting next to a list item.Box Model
Box sizingCopy
* {
box-sizing: border-box;
}iMakes an element's padding and border count toward its total width and height, instead of adding extra size on top. Usually the behavior you want.Width / heightCopy
.box {
width: 200px;
height: 100px;
min-width: 0;
max-width: 100%;
}iSets how big an element is. The min/max versions set a floor or a ceiling so it can never shrink or grow past a certain size.MarginCopy
.box {
margin: 10px;
margin: 10px 20px;
margin: 10px 20px 10px 20px;
margin-inline: auto;
}iThe empty space OUTSIDE an element, which pushes neighboring elements away from it.PaddingCopy
.box {
padding: 10px;
padding: 10px 20px;
padding-block: 10px;
}iThe empty space INSIDE an element, between its edge and its content.BorderCopy
.box {
border: 1px solid #ccc;
border-top: 2px dashed red;
}iDraws a line around an element's edge. You can set its thickness, style, and color, on all sides at once or just one.Display & Positioning
DisplayCopy
.el {
display: block;
display: inline;
display: inline-block;
display: flex;
display: grid;
display: none;
display: contents;
}iControls how an element behaves in the page layout — sitting on its own line, flowing inline with text, becoming a flexible box or a grid, or being hidden entirely.PositionCopy
.el {
position: static;
position: relative;
position: absolute;
position: fixed;
position: sticky;
top: 0;
inset: 0; /* shorthand for top/right/bottom/left */
}iControls how an element is placed on the page — following the normal layout, nudged from where it would normally sit, pinned to a spot, or stuck in place while the page scrolls.Z-indexCopy
.modal {
position: fixed;
z-index: 1000;
}iWhen elements overlap, this decides which one appears on top. A higher number sits in front of a lower one.Float / clearCopy
.img {
float: left;
}
.clearfix {
clear: both;
}iAn older technique that pushes an element to one side and lets text wrap around it.OverflowCopy
.box {
overflow: hidden;
overflow-x: auto;
overflow-y: scroll;
}iDecides what happens when content is too big to fit in its box — get cut off, become scrollable, or show a scrollbar only when it's actually needed.VisibilityCopy
.el {
visibility: hidden; /* keeps layout space */
opacity: 0; /* keeps in flow + interactive */
}iTwo ways to hide something: visibility:hidden hides it but still leaves its empty space behind; opacity:0 makes it invisible while it's still technically there (and clickable, unless you disable that separately).Flexbox
ContainerCopy
.container {
display: flex;
flex-direction: row; /* row | column | row-reverse | column-reverse */
flex-wrap: wrap; /* nowrap | wrap | wrap-reverse */
justify-content: center; /* flex-start | flex-end | center | space-between | space-around | space-evenly */
align-items: center; /* stretch | flex-start | flex-end | center | baseline */
align-content: center; /* for wrapped lines */
gap: 16px;
}iTurns an element into a flexible row or column, giving you easy tools to line up and space out everything inside it.ItemCopy
.item {
flex: 1; /* flex-grow flex-shrink flex-basis */
flex-grow: 1;
flex-shrink: 0;
flex-basis: 200px;
align-self: flex-end;
order: 2;
}iControls how one item inside a flex row/column grows, shrinks, or lines up compared to the items next to it.Grid
ContainerCopy
.grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
grid-template-rows: auto 1fr auto;
gap: 16px;
row-gap: 16px;
column-gap: 24px;
}iTurns an element into a grid, letting you lay out its contents in rows and columns, like a spreadsheet.Item placementCopy
.item {
grid-column: 1 / 3;
grid-column: span 2;
grid-row: 2 / span 3;
}iTells one specific grid item which row/column lines to sit between, or how many cells it should stretch across.Template areasCopy
.grid {
grid-template-areas:
"header header"
"sidebar content"
"footer footer";
}
.header { grid-area: header; }iLets you sketch out your layout as a simple text diagram, then place each element into one of its named regions.AlignmentCopy
.grid {
justify-items: center;
align-items: center;
justify-content: space-between;
place-items: center center; /* align-items justify-items */
}iControls how items line up within their grid cells, or how the whole grid lines up within its own container.Typography
Font shorthandCopy
p {
font: italic bold 16px/1.5 "Space Grotesk", sans-serif;
}iSets several font settings — style, weight, size, line spacing, and family — all in one line instead of five.Text align / decorationCopy
p {
text-align: center;
text-decoration: underline;
text-decoration: underline dotted red;
text-transform: uppercase;
}iControls where text sits (left, center, right), whether it's underlined or struck through, and its letter casing.Line height / spacingCopy
p {
line-height: 1.6;
letter-spacing: 0.02em;
word-spacing: 2px;
}iControls the space between lines of text, and the space between individual letters or words.Overflow textCopy
.truncate {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.clamp {
display: -webkit-box;
-webkit-line-clamp: 3;
-webkit-box-orient: vertical;
overflow: hidden;
}iCuts off text that's too long to fit — either on one line ending in "...", or after a set number of lines.Font loadingCopy
@font-face {
font-family: "Custom";
src: url("/fonts/custom.woff2") format("woff2");
font-display: swap;
}iTells the browser where to download a custom font file from, so you can use it just like any built-in font.Colors & Backgrounds
Color functionsCopy
.el {
color: #333;
color: rgb(51 51 51);
color: rgb(51 51 51 / 50%);
color: hsl(0 0% 20%);
color: oklch(45% 0.03 250);
}iDifferent ways of writing the same color — as a hex code, as red/green/blue numbers, as a hue/saturation/lightness mix, or a newer format.Background shorthandCopy
.el {
background: #fff url("bg.png") no-repeat center / cover;
}iSets an element's background color, image, and how that image repeats, sits, and sizes — all in one line.Background propertiesCopy
.el {
background-color: #fafafa;
background-image: url("bg.png");
background-size: cover; /* contain | 100px 50px */
background-position: center;
background-repeat: no-repeat;
background-attachment: fixed;
}iThe individual settings behind the background shorthand above, useful for when you only need to change one of them.GradientsCopy
.el {
background: linear-gradient(45deg, red, blue);
background: radial-gradient(circle at center, red, blue);
background: conic-gradient(from 0deg, red, yellow, red);
}iCreates a smooth blend between colors as a background — in a straight line, spreading out from a point, or sweeping around like a clock face.Multiple backgroundsCopy
.el {
background:
linear-gradient(rgba(0,0,0,.4), rgba(0,0,0,.4)),
url("photo.jpg") center / cover;
}iLayers more than one background on top of each other, with the first one listed appearing on top.Borders, Radius & Shadows
Border radiusCopy
.card {
border-radius: 8px;
border-radius: 8px 8px 0 0;
border-radius: 50%; /* circle on a square box */
}iRounds the corners of a box. You can round all corners the same amount, or set each one differently.Box shadowCopy
.card {
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
box-shadow: inset 0 0 0 2px #333;
box-shadow: 0 1px 2px red, 0 2px 4px blue; /* stacked */
}iAdds a soft shadow around an element (or, with "inset", inside it). You can even stack several shadows together.OutlineCopy
button:focus-visible {
outline: 2px solid #2684ff;
outline-offset: 2px;
}iDraws a line around an element, similar to a border, but it never squeezes other content — commonly used to show which element is currently selected via keyboard.Text shadowCopy
h1 {
text-shadow: 1px 1px 2px rgba(0,0,0,.4);
}iAdds a soft shadow behind text.Transitions & Animations
TransitionCopy
.btn {
transition: background-color 0.2s ease, transform 0.2s ease;
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}iMakes a style change happen smoothly over time instead of jumping instantly — like a button gently changing color when you hover over it.KeyframesCopy
@keyframes spin {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}iDefines the steps an animation moves through, from a starting look to an ending look (and anything in between).Animation shorthandCopy
.spinner {
animation: spin 1s linear infinite;
/* name duration timing-function delay iteration-count direction fill-mode */
}iPlays one of the animations you defined, controlling how fast it runs, how it eases, and how many times it repeats.Timing functionsCopy
.el {
transition-timing-function: ease;
transition-timing-function: ease-in-out;
transition-timing-function: linear;
transition-timing-function: cubic-bezier(.17,.67,.83,.67);
}iControls the speed curve of a transition or animation — constant speed, easing in or out, or a fully custom curve.Transform & Filter
Transform functionsCopy
.el {
transform: translate(10px, 20px);
transform: translateX(50%);
transform: scale(1.2);
transform: rotate(15deg);
transform: skew(5deg, 0deg);
transform: translate(-50%, -50%) rotate(10deg);
}iMoves, resizes, rotates, or tilts an element visually, without changing the layout of anything else around it.Transform originCopy
.el {
transform-origin: top left;
transform-origin: 50% 50%;
}iSets the point an element rotates or scales around. By default, that's its center.FilterCopy
.img {
filter: blur(4px);
filter: grayscale(100%);
filter: brightness(1.2) contrast(1.1);
filter: drop-shadow(0 4px 6px rgba(0,0,0,.3));
}iApplies a visual effect to an element, like blurring it or turning it grayscale — similar to a photo filter.Backdrop filterCopy
.glass {
background: rgba(255, 255, 255, 0.2);
backdrop-filter: blur(10px);
-webkit-backdrop-filter: blur(10px);
}iBlurs (or otherwise affects) whatever is showing through BEHIND an element — the effect used to create frosted-glass panels.Media & Container Queries
Media queryCopy
@media (min-width: 768px) {
.container { max-width: 720px; }
}
@media (max-width: 767px) { }
@media (orientation: landscape) { }iApplies styles only when the screen matches certain conditions, like being under a certain width — the basis of making a site work well on both phones and desktops.Preference queriesCopy
@media (prefers-color-scheme: dark) {
body { background: #111; color: #eee; }
}
@media (prefers-reduced-motion: reduce) {
* { animation: none !important; transition: none !important; }
}iApplies styles based on a setting on the visitor's own device, like dark mode being turned on, or "reduce motion" being enabled.Container queryCopy
.card-wrap {
container-type: inline-size;
container-name: card;
}
@container card (min-width: 400px) {
.card { flex-direction: row; }
}iLike a media query, but based on the size of a container element rather than the whole screen — so a component can adapt no matter where it's placed on the page.PrintCopy
@media print {
nav, footer { display: none; }
}iApplies styles only when someone prints the page — often used to hide things like navigation menus that don't make sense on paper.Custom Properties & Functions
CSS variablesCopy
:root {
--brand: #131313;
--gap: 16px;
}
.el {
color: var(--brand);
gap: var(--gap, 8px); /* fallback */
}iLets you store a value once, like a brand color, and reuse it everywhere. Unlike Sass variables, these can be read and changed live in the browser.calc()Copy
.el {
width: calc(100% - 40px);
font-size: calc(1rem + 0.5vw);
}iLets you do math directly inside a CSS value, and even mix different units like percent and pixels in the same calculation.clamp() / min() / max()Copy
.el {
font-size: clamp(1rem, 2vw + 1rem, 2.5rem);
width: min(90%, 600px);
padding: max(16px, 2vw);
}iclamp() picks a value that flexes between a minimum and a maximum. min()/max() simply pick the smallest or largest value from a list of options.Scoping with @propertyCopy
@property --angle {
syntax: "<angle>";
initial-value: 0deg;
inherits: false;
}iA more advanced way to define a custom variable that also lets the browser smoothly animate it, which a plain variable can't do.Units
AbsoluteCopy
.el {
width: 100px;
}iA fixed size, measured in pixels, that never changes based on anything else on the page.Relative to fontCopy
.el {
font-size: 1.2rem; /* relative to root */
padding: 1.5em; /* relative to element font-size */
width: 20ch; /* character width */
}iSizes that scale based on font size — either the page's overall base size, or the current element's own font size.Relative to viewportCopy
.el {
width: 100vw;
height: 100vh;
height: 100svh; /* small viewport, mobile-safe */
height: 100dvh; /* dynamic viewport */
}iSizes based on a percentage of the visible screen or browser window.Grid fractionCopy
.grid {
grid-template-columns: 1fr 2fr 1fr;
}iA unit that only works inside CSS Grid, representing a share of whatever space is left over after everything else is sized.PercentagesCopy
.el {
width: 50%;
}iA size relative to something else — usually the size of the parent element.Modern Layout
Gap (flex & grid)Copy
.container {
display: flex;
gap: 12px 24px; /* row-gap column-gap */
}iAdds even spacing between items in a flex or grid layout, without needing to add margin to each item individually.Aspect ratioCopy
.thumb {
aspect-ratio: 16 / 9;
width: 100%;
}iKeeps an element's width and height in a fixed proportion to each other, like 16:9 for a video.Object fitCopy
img {
width: 100%;
height: 200px;
object-fit: cover;
object-position: top;
}iControls how an image or video fills its box when the shapes don't match up — crop it, shrink it to fit, or stretch it.Logical propertiesCopy
.el {
margin-inline: auto;
padding-block: 1rem;
inset-inline-start: 0;
}iSpacing properties that say "start" and "end" instead of "left" and "right", so they automatically adjust for languages that read right-to-left.Scroll snapCopy
.carousel {
display: flex;
overflow-x: auto;
scroll-snap-type: x mandatory;
}
.carousel > * {
scroll-snap-align: start;
}iMakes a scrolling area click neatly into place at set points as you scroll — handy for image carousels.Line clamp / clip-pathCopy
.card {
clip-path: polygon(0 0, 100% 0, 100% 80%, 0 100%);
}iCuts an element into a custom shape you define with a set of points, hiding anything outside that shape.What is this Cheatsheet?
A quick reference for modern CSS, SASS, SCSS, Pug, and React syntax. Switch between tabs to browse selectors, layout, hooks, and more. Click any snippet to copy it, or hover the info icon for an explanation.