CSS — the complete reference
Basics
CSS is the appearance layer. It cascades, it inherits, and it's more powerful than beginners think.
What is CSS?
CSS = Cascading Style Sheets. It controls the appearance and layout of HTML.
- HTML → structure
- CSS → appearance / layout
- JavaScript → behavior
h1 {
color: blue;
font-size: 40px;
}
Result: every <h1> turns blue and 40px.
Ways to add CSS
<!-- inline: on the element -->
<h1 style="color: red;">Hello</h1>
<!-- internal: a style block in the head -->
<style>h1 { color: red; }</style>
<!-- external: linked stylesheet (BEST) -->
<link rel="stylesheet" href="style.css">
External CSS is the professional choice — it separates concerns and caches well. Inline is fine for quick tests, avoid it in real projects.
Syntax
selector {
property: value;
}
p {
color: red; /* selector: p, property: color, value: red */
font-size: 20px;
}
Comments
/* This is a CSS comment */
p {
color: red;
}
Selectors & Cascade
How you target elements — and how the browser decides which rule wins.
Basic selectors
p { } /* element selector: all <p> */
.text { } /* class selector: class="text" */
#title { } /* id selector: id="title" (unique) */
* { } /* universal: everything */
h1, h2, p { } /* grouping */
IDs should be unique; classes are reusable. This is one of the most important topics in CSS.
Attribute selectors
input[type="text"] { } /* exact attribute value */
a[target] { } /* has the attribute */
input[required] { } /* has the attribute */
input[type="email"] { } /* specific value */
[attr] /* present */
[attr="value"] /* equals */
[attr^="value"] /* starts with */
[attr$="value"] /* ends with */
[attr*="value"] /* contains */
Combinators
/* descendant: any p inside div */
div p { }
/* child: direct children only */
div > p { }
/* adjacent sibling: first p right after h1 */
h1 + p { }
/* general sibling: all p after h1 */
h1 ~ p { }
div p selects any depth; div > p only direct children.
Specificity
When multiple rules target the same element, specificity decides the winner:
p { color: blue; } /* low */
.text { color: green; } /* mid */
#title { color: red; } /* high */
<p id="title" class="text">Hello</p>
Priority: !important → inline → ID → class/attribute/pseudo-class → element/pseudo-element. The result here is red.
!important
p {
color: red !important;
}
Forces the declaration to win. It's a sledgehammer — avoid using it routinely. Reach for it only to override third-party or framework styles.
The cascade
"Cascading" is the reason the name exists — many rules combine into one result. With equal specificity, the later rule wins:
p { color: red; }
p { color: blue; } /* blue wins — it comes later */
Inheritance
Some properties flow down to children (like color), others don't (like border):
body { color: blue; } /* text inherits blue down the tree */
color: inherit; /* force: take parent's value */
color: initial; /* force: the default value */
color: unset; /* inherit if inheritable, else initial */
Colors & Backgrounds
The visual vocabulary — every way to write a color, and everything a background can do.
Colors
color: red; /* named */
color: #ff0000; /* hex */
color: #f00; /* hex shorthand */
color: rgb(255, 0, 0); /* rgb */
color: rgba(255, 0, 0, 0.5); /* rgba: alpha 0-1 */
color: hsl(0, 100%, 50%); /* hsl: hue, saturation, lightness */
color: hsla(0, 100%, 50%, 0.5);
color: rgb(255 0 0 / 50%); /* modern space syntax */
All of these are the same red. HSL is the most human-readable for building palettes.
Backgrounds
.box {
background-color: lightblue; /* solid color */
background-image: url("image.jpg"); /* image */
background-repeat: no-repeat; /* repeat / no-repeat / repeat-x / repeat-y */
background-position: center; /* center / top / 10px 20px */
background-size: cover; /* cover / contain / 100% 100% */
}
/* shorthand */
.box {
background: url("image.jpg") center / cover no-repeat;
}
cover fills without stretching (crops); contain fits the whole image (letterboxes).
Units & Values
Pixels are only the beginning. Relative and viewport units make layouts flexible.
Units
/* absolute */
font-size: 20px;
/* relative */
width: 50%; /* % of the parent */
font-size: 2em; /* relative to parent font-size */
font-size: 2rem; /* relative to ROOT font-size — great for scalable layouts */
/* viewport */
width: 50vw; /* 50% of viewport width */
height: 50vh; /* 50% of viewport height */
vmin vmax
/* modern dynamic viewport units */
min-height: 100dvh; /* svh / lvh / dvh */
rem is the safest bet for scalable, consistent spacing and type.
calc()
width: calc(100% - 40px); /* mix units freely */
width: calc(100% - 2rem);
min() / max() / clamp()
width: min(90%, 1200px); /* the smaller of the two */
width: max(300px, 50%); /* the larger of the two */
font-size: clamp(2rem, 5vw, 5rem); /* minimum → preferred → maximum */
/* responsive typography in one line */
h1 { font-size: clamp(2rem, 5vw, 5rem); }
Box Model
Every element is a box. Master this before anything else.
Width & height
.box { width: 300px; height: 200px; }
.box { max-width: 1200px; min-width: 300px; }
.box { min-height: 500px; max-height: 800px; }
Use max-width + % widths for fluid layouts; let height be driven by content.
The box model
From inside out: content → padding → border → margin.
.box {
width: 300px;
padding: 20px; /* space inside, around content */
border: 5px solid black;
margin: 30px; /* space outside, between boxes */
}
One of the most important concepts in CSS — DevTools lets you visualize all four layers.
box-sizing
box-sizing: content-box; /* default: width = content only */
box-sizing: border-box; /* width = content + padding + border */
/* recommended global reset */
*,
*::before,
*::after {
box-sizing: border-box;
}
With border-box, a declared width: 300px stays 300px no matter the padding/border. Life gets dramatically easier.
Margin
.box { margin: 20px; } /* all sides */
.box { margin: 10px 20px 30px 40px; } /* top right bottom left */
.box { margin: 10px 20px; } /* vertical horizontal */
margin-top / margin-right / margin-bottom / margin-left
Padding
.box { padding: 20px; }
.box { padding: 10px 20px; } /* top/bottom 10px, left/right 20px */
.box { padding: 10px 20px 30px 40px; }
Padding is inside the border — it pushes content inward.
Border
border: 1px solid black; /* shorthand */
border-width: 2px;
border-style: solid; /* solid / dashed / dotted / none */
border-color: red;
border-bottom: 2px solid blue; /* one side */
Border radius
border-radius: 10px; /* all corners */
border-radius: 50%; /* circle */
border-radius: 10px 20px 30px 40px;/* top-left top-right bottom-right bottom-left */
Outline
button { outline: 2px solid blue; }
Like a border but it doesn't take layout space — perfect for focus states.
Overflow
overflow: visible; /* default — content spills out */
overflow: hidden; /* clip */
overflow: scroll; /* always show scrollbars */
overflow: auto; /* scrollbars only when needed */
.box {
width: 300px;
height: 100px;
overflow: auto;
}
Display
The switch that decides how a box behaves in the flow.
display
display: block; /* full-width block */
display: inline; /* flows in text */
display: inline-block; /* inline but sized */
display: none; /* removed from layout */
display: flex; /* one-dimensional layout */
display: grid; /* two-dimensional layout */
Block vs inline
- Block — starts on a new line, takes available width (
div,p, headings). - Inline — flows within text, width = content (
span,a,strong). Inline elements ignore width/height.
inline-block
button {
display: inline-block; /* sits inline, but width/height/padding work */
width: 120px;
height: 40px;
}
none vs visibility
display: none; /* element removed entirely — no space */
visibility: hidden; /* invisible BUT keeps its layout space */
Flexbox
One-dimensional layout — a row OR a column. One of the most important CSS skills you'll learn.
Flexbox intro
.container {
display: flex;
}
That single line turns the container into a flex container and its children into flex items aligned on one axis.
flex-direction
flex-direction: row; /* default: left → right */
flex-direction: row-reverse;
flex-direction: column; /* top → bottom */
flex-direction: column-reverse;
justify-content
Aligns items along the main axis:
justify-content: flex-start; /* default */
justify-content: flex-end;
justify-content: center;
justify-content: space-between; /* gaps at edges, space between */
justify-content: space-around;
justify-content: space-evenly;
align-items
Aligns items along the cross axis:
align-items: stretch; /* default: fill the cross axis */
align-items: flex-start;
align-items: center;
align-items: flex-end;
gap
.container {
display: flex;
gap: 20px; /* space between items — no negative margins needed */
}
flex-wrap
.container {
display: flex;
flex-wrap: wrap; /* items flow onto new lines when needed */
}
Essential for responsive navbars and chip rows.
align-content
Aligns multiple flex lines (only visible when wrapping creates lines):
align-content: center;
align-content: space-between;
align-content: stretch;
Flex item properties
.item { flex-grow: 1; } /* how much extra space it takes */
.item { flex-shrink: 1; } /* how fast it shrinks under pressure */
.item { flex-basis: 200px; } /* starting size before grow/shrink */
/* shorthand */
.item { flex: 1; } /* grow:1 shrink:1 basis:0 */
.item { flex: 1 1 200px; } /* grow shrink basis */
flex: 1 on siblings = equal columns that fill the row.
order
.item { order: 2; } /* visual order without touching HTML */
align-self
.item { align-self: flex-end; } /* override alignment for ONE item */
Perfect centering
.container {
display: flex;
justify-content: center; /* main axis */
align-items: center; /* cross axis */
}
The classic two-liner. Memorize it.
Grid
Two-dimensional layout — rows AND columns at once. Extremely important for modern web development.
Grid intro
.container {
display: grid;
}
Flexbox → one axis. Grid → two axes (rows + columns) simultaneously.
grid-template-columns
grid-template-columns: 200px 200px 200px; /* three fixed columns */
grid-template-columns: 1fr 1fr 1fr; /* three flexible, equal columns */
/* fr = fraction of the free space — THE grid unit */
repeat()
grid-template-columns: repeat(3, 1fr); /* 1fr 1fr 1fr */
Grid gap
gap: 20px; /* both axes */
row-gap: 20px;
column-gap: 30px;
Grid rows
grid-template-rows: 100px 200px; /* explicit row heights */
Spanning
.item { grid-column: span 2; } /* occupy 2 columns */
.item { grid-column: 1 / 3; } /* from line 1 to line 3 */
.item { grid-row: span 2; } /* occupy 2 rows */
Grid areas
Name your regions — the most readable way to build a page skeleton:
.container {
display: grid;
grid-template-areas:
"header header"
"sidebar main";
}
.header { grid-area: header; }
.sidebar { grid-area: sidebar; }
.main { grid-area: main; }
Responsive grid
.container {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 20px;
}
This single rule adapts the column count to available space automatically. Card grids everywhere use it.
minmax()
grid-template-columns: repeat(3, minmax(200px, 1fr));
/* each column at least 200px, then grow equally */
auto-fit vs auto-fill
repeat(auto-fit, minmax(250px, 1fr)); /* collapses empty tracks, stretches content */
repeat(auto-fill, minmax(250px, 1fr)); /* keeps empty tracks at min size */
auto-fit is what you want for content grids in almost all cases.
Positioning
Taking boxes out of the normal flow, on purpose.
position
position: static; /* default: normal flow */
position: relative; /* offset from its normal spot */
position: absolute; /* offset from nearest positioned ancestor */
position: fixed; /* offset from the viewport */
position: sticky; /* relative until it hits a threshold, then fixed */
relative
.box {
position: relative; /* ALSO: becomes the anchor for absolute children */
top: 10px;
left: 10px;
}
absolute
.child {
position: absolute;
top: 0;
right: 0;
}
Positioned relative to the nearest positioned ancestor (relative/absolute/fixed/sticky). If none exists, it anchors to the page.
fixed
button {
position: fixed;
bottom: 20px;
right: 20px; /* floating action buttons, chat widgets, navs */
}
Stays glued to the viewport while the page scrolls.
sticky
nav {
position: sticky;
top: 0; /* scrolls normally, then sticks at the top */
}
Sticky headers, sticky table headers, sticky sidebars — all from one declaration.
top / right / bottom / left
.box {
position: absolute;
top: 20px;
left: 30px;
}
Only meaningful on positioned elements (relative/absolute/fixed/sticky).
z-index
.modal {
position: fixed;
z-index: 1000;
}
z-index doesn't automatically mean "on top" — stacking contexts (created by transform, opacity, position, etc.) trap z-index inside them. Check the ancestor chain first.Typography
Most of a website's perceived quality is text rendering. These properties are the daily drivers.
Typography properties
p {
font-family: Arial, sans-serif;
font-size: 18px;
font-weight: 400;
font-style: normal;
line-height: 1.6;
letter-spacing: 0.5px;
word-spacing: 1px;
text-align: left;
text-decoration: none;
text-transform: none;
}
font-family
body {
font-family: "Inter", Arial, sans-serif;
/* browser uses the first font it can load, then the next */
Web fonts
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;700&display=swap" rel="stylesheet">
body { font-family: 'Inter', sans-serif; }
In production, load fonts efficiently (preconnect + font-display: swap).
font-weight
font-weight: 100; /* thin */
font-weight: 400; /* normal */
font-weight: 500; /* medium */
font-weight: 600; /* semi-bold */
font-weight: 700; /* bold */
font-weight: 900; /* black */
font-weight: bold; /* keyword = 700 */
The weight must actually exist in the loaded font file.
line-height
p { line-height: 1.6; } /* unitless = relative to font-size — best practice */
1.5–1.7 reads well for body text. A unitless value inherits proportionally.
text-align
text-align: left; /* default */
text-align: center;
text-align: right;
text-align: justify;
text-decoration
text-decoration: underline;
text-decoration: none; /* remove link underlines */
text-decoration: line-through;
text-decoration: underline wavy red;
text-transform
text-transform: uppercase;
text-transform: lowercase;
text-transform: capitalize;
text-transform: none;
letter-spacing
h1 { letter-spacing: 2px; } /* headlines */
label { letter-spacing: 0.08em; } /* small caps labels */
text-shadow
h1 {
text-shadow: 2px 2px 5px gray;
/* offset-x offset-y blur color */
text-overflow
.title {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis; /* shows "…" when text is too long */
}
Lists
ul { list-style-type: square; }
ul { list-style: none; } /* remove bullets — used for navbars */
Images & Opacity
Making images behave inside fixed-size boxes.
Images
img {
width: 100%;
height: auto; /* keeps aspect ratio */
}
object-fit
img {
width: 300px;
height: 200px;
object-fit: cover; /* fills box, crops overflow */
}
/* cover / contain / fill / none / scale-down */
cover is the go-to for card thumbnails and avatars.
object-position
img {
object-fit: cover;
object-position: center; /* or top, 25% 75%, etc. — which part is visible */
Opacity
.box { opacity: 0.5; } /* 0 = invisible, 1 = fully visible */
Opacity affects the whole element including children (unlike rgba on a background).
Visual Effects
Gradients, shadows, filters and shape clipping — where designs stop looking "default".
Linear gradients
background: linear-gradient(red, blue);
background: linear-gradient(to right, red, blue);
background: linear-gradient(90deg, red, orange, yellow);
Radial gradients
background: radial-gradient(circle, red, blue);
Conic gradients
background: conic-gradient(red, yellow, blue, red);
/* rotates around a center — pie-chart looks, decorative rings */
box-shadow
.card {
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
/* offset-x offset-y blur spread color */
filter
img { filter: grayscale(100%); }
img:hover { filter: brightness(0.8); }
/* blur() brightness() contrast() grayscale() hue-rotate()
invert() opacity() saturate() sepia() */
backdrop-filter
.navbar {
background: rgb(255 255 255 / 70%);
backdrop-filter: blur(10px); /* frosts whatever is BEHIND the element */
mix-blend-mode
.logo { mix-blend-mode: multiply; } /* blends with what's underneath */
Advanced but useful for creative UI.
clip-path
.box { clip-path: circle(50%); }
.arrow {
clip-path: polygon(50% 0, 100% 100%, 0 100%);
}
Don't memorize the syntax — remember that clip-path exists for custom shapes and look it up when needed.
mask
.box {
mask-image: linear-gradient(black, transparent);
/* fade a section into nothing */
CSS Variables
Extremely important for modern development — your design tokens live here.
Variables
:root {
--primary-color: #2563eb;
--spacing: 20px;
}
button {
background: var(--primary-color);
padding: var(--spacing);
}
Define once in :root, use everywhere. Change one line, whole theme updates.
Variable fallback
color: var(--primary-color, blue); /* blue if the variable is missing */
Dark mode pattern
:root {
--bg: white;
--text: black;
}
.dark {
--bg: #111;
--text: white;
}
body {
background: var(--bg);
color: var(--text);
}
Flip the class (or a media query) and the whole theme follows the variables.
Pseudo-classes
Selectors based on state or position — not on what you typed in the markup.
State: hover / active / focus
button:hover { background: blue; } /* mouse over */
button:active { transform: scale(0.95); } /* being pressed */
input:focus { border-color: blue; } /* keyboard / click focus */
/* best for keyboard users: only visible focus rings */
button:focus-visible {
outline: 3px solid blue;
}
Structural pseudo-classes
:first-child
:last-child
:nth-child()
:nth-of-type()
:first-of-type
:last-of-type
:not()
:is()
:where()
:has()
:nth-child()
li:nth-child(2) { color: red; } /* the 2nd item */
li:nth-child(even) { background: #eee; } /* zebra stripes */
li:nth-child(odd) { background: white; }
li:nth-child(3n + 1) { } /* every 3rd starting at 1 */
:not()
button:not(.primary) {
background: gray; /* all buttons EXCEPT .primary */
}
:is()
/* instead of: */
header h1, header h2, header h3 { color: blue; }
/* write: */
header :is(h1, h2, h3) { color: blue; }
:where()
/* like :is() but ZERO specificity — easy to override */
:where(h1, h2, h3) { margin: 0; }
Perfect for base/reset styles you always want to be able to override.
:has()
.card:has(img) {
padding: 0; /* select .card IF it contains an img */
}
Powerful modern selector — the browser's "parent selector".
Pseudo-elements
Style parts of an element that don't exist in the HTML.
Pseudo-elements intro
Pseudo-elements use :: (pseudo-classes use :). The important ones:
::before
::after
::first-letter
::first-line
::selection
::placeholder
::marker
::before
.title::before {
content: "\2605 "; /* inserts content BEFORE the element */
}
::after
.title::after {
content: "";
display: block;
width: 50px;
height: 3px;
background: blue; /* the classic "underline accent" trick */
}
content is required — an empty string is valid, but the pseudo-element won't render without it.::selection
::selection {
background: black;
color: white; /* controls highlighted-text appearance */
}
::placeholder
input::placeholder {
color: gray;
}
Forms & Interaction
Making form controls look intentional and behave predictably.
Styling forms
input, textarea, select, button {
font: inherit; /* forms don't inherit fonts by default — fix that */
}
input {
padding: 10px;
border: 1px solid #ccc;
border-radius: 6px;
}
Form states
input:focus { outline: none; border-color: blue; }
input:required { border-color: orange; }
button:disabled { opacity: 0.5; cursor: not-allowed; }
input:valid { border-color: green; }
input:invalid { border-color: red; }
cursor
button { cursor: pointer; }
cursor: not-allowed;
cursor: grab;
cursor: wait;
cursor: text;
pointer-events
.overlay { pointer-events: none; } /* clicks pass THROUGH it */
user-select
button { user-select: none; } /* prevent text selection */
Don't overuse on normal text — selection is an accessibility feature.
Motion
Transitions smooth property changes; transforms move elements; animations tell stories.
Transitions
button {
background: blue;
transition: background 0.3s ease;
}
button:hover { background: red; } /* animates over 0.3s */
Transition shorthand
transition: all 0.3s ease; /* everything — convenient but blunt */
/* better: name the properties you animate */
transition:
transform 0.3s ease,
background-color 0.3s ease;
transform
transform: translateX(50px); /* move */
transform: scale(1.2); /* resize */
transform: rotate(45deg); /* spin */
transform: skewX(20deg); /* tilt */
/* combine multiple */
transform: translateX(20px) rotate(10deg) scale(1.1);
Transforms don't affect layout and are GPU-friendly — the go-to for smooth hover motion.
transform-origin
.box { transform-origin: center; }
.box { transform-origin: top left; } /* the pivot point */
@keyframes
@keyframes slide {
from { transform: translateX(0); }
to { transform: translateX(200px); }
}
.box {
animation: slide 2s ease infinite;
}
Animation properties
.box {
animation-name: slide;
animation-duration: 2s;
animation-delay: 0.5s;
animation-iteration-count: infinite; /* or 3, or 1 */
animation-direction: alternate; /* reverse on alternate runs */
animation-fill-mode: forwards; /* keep end state */
animation-play-state: running; /* or paused */
animation-timing-function: ease;
}
Timing functions
ease /* default: slow start & end */
linear /* constant speed */
ease-in /* starts slow */
ease-out /* ends slow */
ease-in-out /* slow both ends */
cubic-bezier(0.17, 0.67, 0.83, 0.67) /* custom curve */
Responsive
One page, every screen — mobile, tablet, laptop, desktop.
Responsive design
Your toolkit:
- Flexible widths (
%,fr,min()) - Flexbox & Grid
- Responsive units (
rem,vw/vh) - Media queries
- Fluid typography (
clamp()) - Responsive images (
srcset)
Media queries
@media (max-width: 768px) {
.container { flex-direction: column; }
}
/* applies when the viewport is 768px or narrower */
Mobile-first
.card { width: 100%; } /* base = mobile */
@media (min-width: 768px) {
.card { width: 50%; } /* enhance = larger screens */
}
Start with the mobile styles, then progressively enhance with min-width queries.
Responsive container
.container {
width: min(90%, 1200px);
margin-inline: auto; /* centers horizontally */
}
/* or the classic version */
.container {
max-width: 1200px;
width: 90%;
margin: 0 auto;
}
scroll-behavior
html { scroll-behavior: smooth; } /* smooth anchor jumps */
Scroll snap
.container {
overflow-x: auto;
scroll-snap-type: x mandatory; /* or y / both, proximity */
}
.item {
scroll-snap-align: start; /* items lock into place */
}
For carousels and horizontal gallery sections.
Scrollbars
.box {
scrollbar-width: thin; /* Firefox — simple */
}
WebKit pseudo-elements exist too, but support varies. Style sparingly.
Modern CSS
The CSS of today — logical directions, containers, nesting and more. Learn these and you'll write less and less hacks.
Logical properties
Instead of physical directions (left/right), logical ones follow the writing direction:
margin-left: 20px; /* physical */
margin-inline-start: 20px; /* logical — flips for RTL languages */
margin-inline /* start + end (horizontal) */
margin-block /* top + bottom (vertical) */
padding-inline / padding-block
border-inline / border-block
inset-inline / inset-block
Especially useful for multilingual and RTL layouts.
inset
/* instead of: */
top: 0; right: 0; bottom: 0; left: 0;
/* write: */
inset: 0;
.overlay {
position: absolute;
inset: 0;
}
aspect-ratio
.video {
width: 100%;
aspect-ratio: 16 / 9; /* height derives from width automatically */
}
Card image pattern
.card img {
width: 100%;
aspect-ratio: 16 / 9; /* consistent crop box */
object-fit: cover; /* crop instead of stretch */
}
The standard for card thumbnails.
CSS functions
Know these by name — you'll reach for them constantly:
var()
calc()
min()
max()
clamp()
rgb()
hsl()
url()
attr()
width: calc(100% - 20px);
font-size: clamp(1rem, 3vw, 2rem);
attr()
<div data-label="Hello"></div>
div::before {
content: attr(data-label); /* reads the attribute */
}
CSS nesting
.card {
padding: 20px;
& h2 { color: blue; }
&:hover { transform: translateY(-5px); }
}
Native nesting — cleaner, more readable component styles.
@media
@media (max-width: 768px) {
body { font-size: 14px; }
}
@supports
Feature detection — apply styles only if the browser supports something:
@supports (display: grid) {
.container { display: grid; }
}
The engine of progressive enhancement.
@font-face
@font-face {
font-family: "MyFont";
src: url("myfont.woff2") format("woff2");
}
body { font-family: "MyFont", sans-serif; }
@import
@import url("theme.css");
Possible, but bundlers and explicit <link> tags are generally better for performance.
CSS reset
Browsers ship default styles. Start from a clean baseline:
*,
*::before,
*::after {
box-sizing: border-box;
}
html, body {
margin: 0;
padding: 0;
}
img {
max-width: 100%;
display: block;
}
button, input, textarea, select {
font: inherit;
}
Or use an established reset/normalize instead of a custom monster.
margin-inline: auto
.container {
width: 80%;
margin-inline: auto; /* classic horizontal centering */
}
Centering with grid
.container {
display: grid;
place-items: center; /* both axes at once — very convenient */
}
place-items / place-content / place-self
place-items: center; /* align-items + justify-items */
place-content: center; /* align-content + justify-content */
place-self: center; /* align-self + justify-self (one item) */
overflow-wrap
.text { overflow-wrap: break-word; }
.text { word-break: break-word; }
.text { hyphens: auto; }
For long URLs and unbroken strings inside tight layouts.
white-space
white-space: nowrap; /* no wrapping — combine with ellipsis */
white-space: normal; /* default */
white-space: pre;
white-space: pre-wrap;
white-space: pre-line;
Tables in CSS
table {
border-collapse: collapse;
}
td, th {
border: 1px solid #ddd;
padding: 10px;
}
currentColor
.icon { color: blue; }
.icon svg {
fill: currentColor; /* the SVG follows the parent text color */
}
inherit / initial / unset / revert
color: inherit; /* take the parent's value */
color: initial; /* the property's default */
color: unset; /* inherit if inheritable, otherwise initial */
all: revert; /* undo author styles back to the user-agent */
all
button { all: unset; } /* wipe every style — use carefully */
content-visibility
.section {
content-visibility: auto; /* skip rendering work for off-screen content */
}
A performance tool for long pages. Use intentionally, not blindly.
Containment
.card {
contain: layout paint; /* isolate layout & painting work */
}
Advanced — useful in large, complex interfaces.
Counters
body { counter-reset: section; }
h2::before {
counter-increment: section;
content: counter(section) ". ";
}
Automatic numbering without touching the HTML.
accent-color
input[type="checkbox"] {
accent-color: blue; /* colors native form controls */
}
appearance
button { appearance: none; } /* strip native chrome to build custom */
Powerful for custom controls — just don't remove important affordances carelessly.
Accessibility CSS
Never remove focus indicators without replacing them:
/* bad: */
button { outline: none; }
/* good: */
button:focus-visible {
outline: 3px solid blue;
outline-offset: 3px;
}
Reduced motion
@media (prefers-reduced-motion: reduce) {
*,
*::before,
*::after {
animation-duration: 0.01ms;
animation-iteration-count: 1;
transition-duration: 0.01ms;
scroll-behavior: auto;
}
}
Essential for vestibular-motion accessibility.
Dark / light preference
@media (prefers-color-scheme: dark) {
body { background: #111; color: white; }
}
Container queries
Instead of responding to the viewport, respond to the container's size — perfect for reusable components:
.card-wrapper {
container-type: inline-size;
}
@container (min-width: 500px) {
.card { display: flex; }
}
Cascade layers
@layer reset, base, components, utilities;
@layer reset {
* { box-sizing: border-box; }
}
@layer components {
.button { padding: 10px 20px; }
}
Layers give you explicit control over cascade order across whole stylesheets — increasingly useful on large projects.
Architecture
Beyond one giant stylesheet — how professionals organize CSS at scale.
CSS architecture
Don't dump everything into one file. A common conceptual split:
styles/
reset.css
variables.css
base.css
components.css
utilities.css
responsive.css
In React/Next, component-scoped styling often replaces this — the principle (separation) stays.
Utility classes
.flex { display: flex; }
.items-center { align-items: center; }
.justify-center { justify-content: center; }
.gap-4 { gap: 1rem; }
The basic idea behind utility-first systems like Tailwind CSS.
BEM
<div class="card">
<h2 class="card__title">Hello</h2>
<button class="card__button">Read</button>
</div>
<div class="card card--featured">...</div>
Pattern: block__element--modifier. Predictable, collision-free naming.
Debugging with DevTools
You must know the browser DevTools (Chrome: F12 or Ctrl+Shift+I). Key panels:
- Elements — inspect the DOM
- Styles — see which rules apply, toggle them live
- Computed — what the browser actually computed
- Layout — box model visualization
- Console — errors and logs
- Network — requests and load times
Inspecting the box model
When something doesn't align, open DevTools → Elements → the Layout tab. You'll see margin / border / padding / content layers for the selected element. It answers "why is this 340px when I said 300px?" instantly.
Common CSS problems
- "Width isn't working" → the element may be
display: inline. - "z-index isn't working" → check position and stacking contexts up the tree.
- "height: 100% does nothing" → the parent has no definite height.
- "Content is overflowing" → check width + padding,
box-sizing,min-width,white-space,overflow.
Shorthand
/* instead of four lines: */
margin-top: 10px; margin-right: 20px;
margin-bottom: 10px; margin-left: 20px;
/* write: */
margin: 10px 20px;
/* same idea: padding, border, background, font, transition, animation, flex */
min-width: 0
.item {
min-width: 0; /* stops flex/grid items from blowing past their track */
}
The classic flexbox/grid fix for long unbreakable content.
Layers of layout
When debugging a UI, reason in this order:
1. Display
2. Position
3. Width / Height
4. Box model
5. Flex / Grid
6. Typography
7. Visual styling
8. Animation
This mindset saves hours of debugging.
Mastery
The finish line: what to prioritize, a real example, and the path forward.
Units you must master
px % rem em vw vh dvh fr auto
min() max() clamp()
That's the practical set. You don't need to memorize every CSS unit equally.
Properties to memorize
display position top/right/bottom/left z-index
width height min-width max-width min-height max-height
margin padding border border-radius box-sizing
color background background-size background-position
font-family font-size font-weight line-height text-align
overflow opacity
flex flex-direction flex-wrap justify-content
align-items align-self gap
grid-template-columns grid-template-rows
grid-column grid-row grid-area
transform transition animation
object-fit aspect-ratio cursor
Know these cold. Everything else is a lookup away.
Concepts you must master
- Level 1 · Foundation — selectors, cascade, specificity, inheritance, colors, units, box model, display.
- Level 2 · Layout — Flexbox, Grid, position, z-index, overflow, responsive, media queries.
- Level 3 · UI — typography, backgrounds, gradients, shadows, forms, pseudo-classes/elements, transitions, transforms, animations.
- Level 4 · Modern — variables, calc, min/max/clamp, aspect-ratio, object-fit, :is/:where/:has, container queries, nesting, cascade layers, logical properties.
- Level 5 · Professional — accessibility, responsive, architecture, BEM/utilities, DevTools, performance, component styling.
Complete example
All the concepts, together — a realistic responsive product card.
<div class="container">
<article class="card">
<img src="image.jpg" alt="Product" class="card__image">
<div class="card__content">
<h2 class="card__title">Web Development Course</h2>
<p class="card__description">Learn modern HTML, CSS and JavaScript.</p>
<button class="card__button">Learn More</button>
</div>
</article>
</div>
:root {
--primary: #2563eb;
--text: #111827;
--muted: #6b7280;
--radius: 12px;
}
*, *::before, *::after { box-sizing: border-box; }
body {
margin: 0;
font-family: Arial, sans-serif;
color: var(--text);
background: #f3f4f6;
}
.container {
width: min(90%, 1200px);
margin-inline: auto;
padding-block: 40px;
display: grid;
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
gap: 24px;
}
.card {
background: white;
border-radius: var(--radius);
overflow: hidden;
box-shadow: 0 10px 30px rgb(0 0 0 / 10%);
transition: transform 0.3s ease, box-shadow 0.3s ease;
}
.card:hover {
transform: translateY(-5px);
box-shadow: 0 15px 40px rgb(0 0 0 / 15%);
}
.card__image {
width: 100%;
aspect-ratio: 16 / 9;
object-fit: cover;
}
.card__content { padding: 20px; }
.card__title {
margin: 0 0 10px;
font-size: clamp(1.2rem, 3vw, 1.6rem);
}
.card__description {
margin: 0 0 20px;
color: var(--muted);
line-height: 1.6;
}
.card__button {
border: 0;
border-radius: 8px;
padding: 12px 20px;
background: var(--primary);
color: white;
cursor: pointer;
transition: background 0.3s ease, transform 0.2s ease;
}
.card__button:hover { background: #1d4ed8; }
.card__button:active { transform: scale(0.97); }
.card__button:focus-visible {
outline: 3px solid #93c5fd;
outline-offset: 3px;
}
Demonstrates: variables, reset, box-sizing, responsive width, Grid + auto-fit + minmax, gap, margin-inline, padding-block, radius, shadow, transitions, transform, aspect-ratio, object-fit, clamp, :hover/:active/:focus-visible, accessibility, responsive design.
What not to memorize
Don't try to memorize hundreds of properties. Understand how CSS works and look up the uncommon stuff:
/* don't memorize: */
clip-path: polygon(50% 0, 100% 100%, 0 100%);
/* do remember: */
/* "CSS has clip-path for custom shapes." → look it up when needed */
The CSS mental model
HTML
↓ DOM structure
↓ Selectors
↓ Cascade + Specificity
↓ Box model
↓ Display
↓ Flex / Grid
↓ Positioning
↓ Responsive behavior
↓ Typography
↓ Colors / backgrounds
↓ Transitions / animations
If you understand this chain, CSS becomes much easier.
Learning order
01. Syntax 24. Transitions
02. Selectors 25. Transform
03. Cascade 26. Animations
04. Specificity 27. CSS Variables
05. Inheritance 28. calc()
06. Colors 29. min / max / clamp
07. Units 30. aspect-ratio
08. Box model 31. object-fit
09. Width / height 32. Gradients
10. Margin / padding 33. Shadows
11. Border 34. Logical properties
12. Display 35. :is() / :where() / :has()
13. Typography 36. Container queries
14. Backgrounds 37. CSS nesting
15. Flexbox 38. Cascade layers
16. Grid 39. Accessibility
17. Position 40. DevTools
18. z-index 41. Architecture
19. Overflow 42. Performance
20. Responsive
21. Media queries
22. Forms
23. Pseudo-classes / elements
The bottom line: if you can build a responsive navbar, landing page, dashboard, product grid, login/register form, sidebar, modal, pricing section, portfolio and a full responsive website — your CSS is in a strong place. Move on to JavaScript and come back here to revise.