Interactive CSS CodePen
Active: border-radius template
HTML (Source Structure)
CSS (Active Styling)
🛠️ Chrome DevTools Tuning
Live Output Canvas (Real-time Rendering)
01 — Box Model
The CSS Box Model CSS3
Every element is a rectangular box composed of four areas: content, padding, border,
and margin. Understanding this is fundamental to layout.
Box Model Essentials:
Content- The text or image bounding dimensions. Affected bybox-sizing.Padding- Transparent inner breathing space. Inherits element background properties.Border- Outlines the padding area. Thickness, style, and colors are fully custom.Margin- Exterior separation space clearing other boxes. Collapses vertically on adjacent blocks.
Margin
Border
Padding
Content
width × height
width × height
.box {
width:200px;
/* content width */
height:100px;
/* content height */
padding:20px;
/* space inside border */
border:2pxsolid#333;
/* border thickness */
margin:10px;
/* space outside border */
/* Total = 200 + 40 + 4 = 244px wide */
}
/* Fix: include padding+border IN the width */* {
box-sizing:border-box;
}
Width & Height
Control element dimensions with fixed, relative, or constrained values.
.element {
width:300px;
/* fixed */
width:50%;
/* relative to parent */
width:auto;
/* browser decides */
width:50vw;
/* 50% viewport width */
min-width:200px;
max-width:800px;
height:100vh;
/* full viewport */
aspect-ratio:16/9;
/* NEW ✨ */
}
Box Sizing (Sizing Reset) ESSENTIAL
Control how the total width and height of an element are calculated (including border
and padding).
Content-Box vs Border-Box:
- content-box (Default): Width/height only apply to the content. Padding and border are added on top, expanding the element's actual size (e.g. 100px width + 20px padding + 2px border = 122px total).
- border-box (Recommended): Width/height apply to the total size. Padding and border are absorbed inside (e.g. 100px width includes padding/borders, keeping total size exactly 100px).
/* 1. Global Box Sizing Reset (The Professional Web Standard) */*, *::before, *::after {
box-sizing: border-box;
}
/* 2. Traditional default (Padding & borders ADDED to size) */.legacy-card {
box-sizing: content-box;
/* default browser behavior */
width: 200px;
padding: 20px;
border: 5pxsolid black;
/* Calculated Total Visual Width = 200 + 40(padding) + 10(borders) = 250px! */
}
/* 3. Fluid layout default (Padding & borders ABSORBED inside size) */.modern-card {
box-sizing: border-box;
/* elements keep their exact declared size */
width: 200px;
padding: 20px;
border: 5pxsolid black;
/* Calculated Total Visual Width = exactly 200px! Content area shrinks to 150px.
*/
}
Padding & Margin
Padding is inside the border; margin is outside. Use shorthand: top right bottom
left.
/* All sides */
padding:20px;
/* Vertical | Horizontal */
padding:10px20px;
/* Top | H | Bottom */
padding:10px20px15px;
/* Top Right Bottom Left */
padding:5px10px5px20px;
/* Center a block */
margin:0auto;
/* Negative margin */
margin-top:-20px;
02 — Typography
Font Properties
Control typeface, size, weight and style of text.
p {
/* 1. Standard Font Properties */
font-family: 'Inter', system-ui, sans-serif;
font-size: 1.25rem;
/* 20px */
font-weight: 600;
/* Semi-bold (100 to 900) */
font-style: italic;
/* 2. Spacing & Legibility */
line-height: 1.6;
/* Unitless multiplier is best practice! */
letter-spacing: -0.02em;
/* Tighter tracking for large headings */
word-spacing: 0.1em;
/* 3. The Font Shorthand (Format: style weight size/line-height family) */
font: italic7002rem/1.2'Inter', sans-serif;
}
Text Properties
Alignment, decoration, transform, and overflow handling for text.
.text {
text-align:center;
/* left|right|justify */
text-decoration:underline#f00wavy;
text-transform:uppercase;
/* lowercase|capitalize */
text-shadow:2px2px4pxrgba(0,0,0,.3);
text-indent:2em;
white-space:nowrap;
overflow:hidden;
text-overflow:ellipsis;
/* truncate → … */
word-break:break-word;
}
03 — Colors & Backgrounds
Color Formats
CSS supports multiple color formats — each with specific use cases.
color:red;
/* keyword */
color:#ff5733;
/* hex */
color:#f53;
/* hex shorthand */
color:rgb(255,87,51);
color:rgba(255,87,51,0.8);
color:hsl(11,100%,60%);
color:hsla(11,100%,60%,0.5);
color:oklch(0.70.230);
/* new! */
opacity:0.8;
/* 0–1 */
Background Properties
Control background color, images, gradients, and positioning. Backgrounds can dramatically enhance layout design.
background-size: cover vs contain
cover
contain
background-repeat & position
repeat-x
center no-repeat
background-clip: text (Text Masking)
VIBRANT DESIGN
.hero {
background-color:#0b0c10;
background-image:url('bg-pattern.png');
background-size:cover; /* cover|contain|auto|100% */
background-position:center;
background-repeat:no-repeat; /* repeat-x|repeat-y|space */
background-attachment:fixed; /* parallax effect */
/* The Shorthand Property */
background: #0b0c10 url('bg-pattern.png') no-repeat center center / cover;
}
.text-mask {
background-image:url('bg-pattern.png');
-webkit-background-clip:text;
-webkit-text-fill-color:transparent;
}
Border & Outline
Borders surround padding; outlines float outside and don't affect layout.
.card {
border:2pxsolid#333;
/* shorthand */
border-top:4pxdashed#f00;
border-radius:12px;
/* rounded corners */
border-radius:50%;
/* circle */
border-radius:10px20px10px20px;
/* Outline (no layout shift) */
outline:2pxsolid#00e5ff;
outline-offset:4px;
/* Box shadow */
box-shadow:04px20pxrgba(0,0,0,.2);
}
04 — Display & Visibility
Display Property
Controls how an element participates in the flow layout.
Display Mode Quick Cheat:
block- Occupies full horizontal row. Ignores surrounding elements, starts new line.inline- Flows naturally inside text content. Binds vertical margins/padding cleanly.inline-block- Flows like text but enables specifying precise box width/height values.none- Completely hides the element and removes its layout footprint entirely from DOM.
display:block;
/* full row */
display:inline;
/* flow with text */
display:inline-block;
/* inline + box props */
display:flex;
/* flexbox container */
display:grid;
/* grid container */
display:none;
/* hide + remove */
display:contents;
/* transparent box */
display:table;
/* table layout */
/* Visibility vs display */
visibility:hidden;
/* hides but keeps space */
opacity:0;
/* invisible but interactive */
Position Property
Controls element positioning scheme in the document.
Positioning Coordinate Systems:
relative- Standard position flow, but offset elements from their original coordinates.absolute- Completely out of flow. Positions absolute offsets relative to nearest positioned parent.fixed- Detached coordinate boundaries pinned directly relative to the active viewport canvas.sticky- Behaves relative until scroll meets a threshold, then locks in fixed position coordinates.
position:static;
/* default, in flow */
position:relative;
/* offset from itself */
position:absolute;
/* out of flow */
position:fixed;
/* relative to viewport */
position:sticky;
/* scroll until stuck */.overlay {
position:absolute;
top:0;
right:0;
bottom:0;
left:0;
/* center absolute element */
top:50%;
left:50%;
transform:translate(-50%,-50%);
}
Overflow & Z-Index
Control what happens when content overflows its container, and layering order.
.container {
overflow:hidden;
/* clip content */
overflow:scroll;
/* always scrollbar */
overflow:auto;
/* scrollbar if needed */
overflow-x:hidden;
overflow-y:scroll;
/* Clip without BFC */
overflow:clip;
/* Stacking order */
z-index:10;
/* must have position */
z-index:-1;
/* behind parent */
}
05 — Selectors
CSS Selectors Reference
| Selector | Example | Description |
|---|---|---|
| Universal | * | Selects all elements |
| Type | div, p, h1 | Selects all elements of that type |
| Class | .className | Selects elements with that class |
| ID | #idName | Selects single element with that ID |
| Descendant | div p | Selects p inside any div |
| Child | div > p | Selects direct child p of div |
| Adjacent | h1 + p | Selects first p immediately after h1 |
| Sibling | h1 ~ p | Selects all p siblings after h1 |
| Attribute | [type="text"] | Selects elements with that attribute |
| Attr contains | [class*="btn"] | Attribute value contains "btn" |
| Attr starts | [href^="https"] | Attribute value starts with "https" |
| Attr ends | [src$=".jpg"] | Attribute value ends with ".jpg" |
06 — Pseudo-Classes & Elements
Pseudo-Classes
Style elements based on their state or position.
:hover
Mouse over element
:focus
Focused (keyboard/click)
:active
Being clicked
:visited
Visited link
:first-child
First sibling
:last-child
Last sibling
:nth-child(n)
nth sibling (even/odd)
:not(sel)
Not matching selector
:checked
Checked input
:disabled
Disabled form element
:empty
No children
:is()
Matches any listed
Pseudo-Elements
Style specific parts of an element using double colon.
/* Insert content before/after */.btn::before {
content:"→ ";
color:#00e5ff;
}
.note::after {
content:" ★";
}
/* First letter/line */p::first-letter {
font-size:3em;
float:left;
}
p::first-line {
font-weight:bold;
}
/* Selection highlight */::selection {
background:#ff4081;
color:#fff;
}
/* Placeholder text */::placeholder {
color:#999;
}
07 — Specificity
CSS Specificity & Cascade
When multiple rules target the same element, specificity determines which wins.
Higher = wins.
!important
Inline style
#id
.class / :pseudo
element
/* Specificity Scores: [Inline Style, ID, Class/Pseudo, Element] */
/* 1. Element Selector — Score: [0, 0, 0, 1] = 1 Point */p {
color: blue;
}
/* 2. Class Selector — Score: [0, 0, 1, 0] = 10 Points (WINS over element)
*/.text-highlight {
color: green;
}
/* 3. Multi-class + element — Score: [0, 0, 2, 1] = 21 Points */p.text-highlight.active {
color: orange;
}
/* 4. ID Selector — Score: [0, 1, 0, 0] = 100 Points (WINS over all classes!)
*/#main-heading {
color: red;
}
/* 5. Inline Style — Score: [1, 0, 0, 0] = 1000 Points (WINS over external IDs)
*/
/* Applied in HTML: < p style="color: purple; "> */
/* 6. !important Override — Score: ∞ Infinite! Beats everything including inline
*/p {
color: hotpink!important;
/* ⚠ Avoid !important — refactor to higher-specificity selectors instead */
}
Inheritance & Global Keywords
Control how elements receive styling from their ancestors, and force properties to
reset or revert.
Global CSS Value Keywords:
- inherit: Forces the element to adopt the exact calculated value of its parent element.
- initial: Resets the property to its official default CSS specification value (e.g.
inlinefor display). - unset: Behaves like
inheritif the property naturally inherits, otherwise likeinitial. - revert: Rolls back the property to the browser's default user-agent stylesheet style.
.child-element {
/* Force text color to match its parent */
color: inherit;
/* Completely reset margins to browser default spec */
margin: initial;
/* Revert display property to user-agent styles */
display: revert;
/* Reset property based on natural inheritance rules */
all: unset;
}
01 — Flexbox
Flexbox Container Properties POPULAR
Flexbox is a one-dimensional layout system that arranges elements along a main axis
and cross axis. The parent is designated as the "flex container" which controls alignment, wrapping, and
spacing of all its child "flex items".
Core Axis System & Alignments:
flex-direction: rowdefines horizontal as the Main Axis, vertical as the Cross Axis.flex-direction: columnrotates the system, making vertical the Main Axis and horizontal the Cross Axis.justify-contentgoverns alignment along the Main Axis (e.g., center, space-between, space-evenly).align-itemsgoverns single-line alignment along the Cross Axis (e.g., stretch, center, baseline).align-contentgoverns alignment of multi-line wraps along the Cross Axis (only works whenflex-wrap: wrapis active).
.flex-container {
display: flex;
/* establishes flex context (inline-flex also valid) */
/* 1. Main Axis & Wrap Configuration */
flex-direction: row;
/* row (default) | row-reverse | column | column-reverse */
flex-wrap: wrap;
/* nowrap (default) | wrap | wrap-reverse */
flex-flow: row wrap;
/* Shorthand:
*/
/* 2. Main Axis Item Distribution (justify-content) */
justify-content: space-evenly;
/* flex-start | flex-end | center | space-between | space-around */
/* 3. Cross Axis Single Line Alignment (align-items) */
align-items: center;
/* stretch (default) | flex-start | flex-end | center | baseline */
/* 4. Cross Axis Multi-Line Row Distribution (align-content) */
align-content: space-between;
/* stretch | flex-start | flex-end | center | space-around | space-evenly */
/* 5. Modern Combined Alignment shorthand */
place-content: space-between center;
/* Shorthand: */
/* 6. Spacing Gaps (modern margins replacement) */
gap: 1rem1.5rem;
/* Shorthand: */
row-gap: 1rem;
column-gap: 1.5rem;
}
Flex Item Properties
Govern how individual child items within a flex container resize, grow, shrink,
stack, and align themselves regardless of their sibling properties.
The Magic Flex Shorthand:
flex: <grow> <shrink> <basis> is strongly preferred over individual
properties.
flex: 1(expands as1 1 0%): Fills all available horizontal space proportionally.flex: 0 0 auto: Fixed size. Will neither grow nor shrink, keeping its native content boundaries.flex: 0 1 auto: Standard default layout. Does not grow, shrinks if parent runs out of room.flex: 1 0 250px: Expandable, but establishes a 250px lower limit (won't shrink below this).
.flex-item {
/* 1. Flex Sizing Parameters */
flex-grow: 1;
/* sizing factor relative to siblings (default = 0) */
flex-shrink: 1;
/* shrink priority factor when container shrinks (default = 1) */
flex-basis: auto;
/* starting dimension before dividing space (e.g. 250px, 20%) */
/* 2. Unified Shorthand (Highly Recommended) */
flex: 11auto;
/* Shorthand:
*/
/* 3. Cross Axis Alignment Override */
align-self: self-end;
/* auto | stretch | flex-start | flex-end | center | baseline */
/* 4. Display Stack Order */
order: 2;
/* index priority (default = 0, can be negative) */
}
02 — CSS Grid
CSS Grid Layout POPULAR
CSS Grid is a highly powerful two-dimensional layout engine, operating along both
rows and columns simultaneously. Perfect for structural page wireframing and complex dashboard interfaces.
The Magic of Auto-Responsive Grid Tracks:
Create a 100% responsive, wrapping card column layout without using a single CSS media query:
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
repeat()tells the browser to replicate a pattern across the track space.minmax(250px, 1fr)ensures no card falls below 250px, but expands up to 1 fractional unit of space.auto-fitcollapses empty tracks to let current cards expand. Alternateauto-fillleaves empty tracks empty.
.grid-container {
display: grid;
/* establishes grid context (inline-grid also valid) */
/* 1. Explicit Column & Row Sizing templates */
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
grid-template-rows: 80px1fr60px;
/* 2. Custom Named Line Template definition */
grid-template-columns: [main-start]1fr[main-end sidebar-start]250px[sidebar-end];
/* 3. Structural Template Area Mapping */
grid-template-areas: "header header""content sidebar""footer footer";
/* 4. Combined Template Shorthand */
grid-template: "header header"80px"content sidebar"1fr"footer footer"60px/ 1fr250px;
/* 5. Implicit Track Overflow Configuration */
grid-auto-flow: row dense;
/* row (default) | column | dense | row dense | column dense */
grid-auto-rows: minmax(100px, auto);
/* implicit track height */
grid-auto-columns: 200px;
/* implicit track width */
/* 6. Item Cell Placement Alignments */
justify-items: stretch;
/* stretch | start | end | center */
align-items: center;
/* stretch | start | end | center */
place-items: center stretch;
/* Shorthand: */
/* 7. Align Whole Track Grid inside outer container */
justify-content: space-between;
/* space-between | center | start | end | space-around */
align-content: space-evenly;
/* space-evenly | center | start | end | space-between */
place-content: space-evenly space-between;
/* Shorthand: */
/* 8. Separation gaps */
gap: 1.5rem;
}
Grid Item Placement & Spanning
Position individual child items inside a CSS Grid using line numbers, column spans,
or areas.
Shorthand Positioning Guide:
grid-column: [start-line] / [end-line](or usespan [number]to stretch).- Grid lines are 1-indexed, starting from the left/top edge. A negative index (like
-1) represents the last line.
.grid-item {
/* 1. Explicit Line Placements */
grid-column-start: 1;
grid-column-end: 3;
grid-row-start: 2;
grid-row-end: 4;
/* 2. Placement Shorthands (Highly Preferred) */
grid-column: 1/ 3;
/* / */
grid-row: 2/ span2;
/* start at 2, stretch across 2 cells */
/* 3. Full-width Screen references */
grid-column: 1/ -1;
/* locks from column 1 to last screen edge (-1) */
/* 4. Named Line references */
grid-column: main-start/ sidebar-end;
/* 5. Area Template Binding */
grid-area: content;
/* matches grid-template-areas declaration */
/* 6. Single Item Cell overrides */
justify-self: center;
/* stretch | start | end | center */
align-self: end;
/* stretch | start | end | center */
place-self: end center;
/* Shorthand: */
}
03 — Transitions & Transforms
CSS Transitions
Smoothly animate between CSS property values on state change.
.btn {
/* 1. Direct Properties to Animate */
transition-property: background-color, transform,
box-shadow;
/* 2. Pace & Durations */
transition-duration: 0.4s;
transition-delay: 0s;
/* start instantly */
/* 3. Easing Timing Functions */
transition-timing-function: cubic-bezier(0.175, 0.885, 0.32,
1.275);
/* Bouncy physics */
transition-timing-function: ease-in-out;
/* Soft acceleration & deceleration */
transition-timing-function: steps(4);
/* Retro, frame-by-frame mechanical jump */
/* 4. Unified Shorthand (Highly Recommended) */
transition: transform0.3scubic-bezier(0.175, 0.885, 0.32, 1.275)0s;
/* Shorthand formula:
*/
/* 5. Animating multiple properties with varying speeds */
transition: background-color0.3sease, transform0.2sease-in-out;
}
CSS Transform
Translate, rotate, scale, and skew elements without affecting layout.
.element {
/* Move */
transform:translate(50px,-20px);
transform:translateX(50%);
/* Rotate */
transform:rotate(45deg);
transform:rotateY(180deg);
/* 3D */
/* Scale */
transform:scale(1.2);
transform:scaleX(0.5);
/* Skew */
transform:skew(10deg);
/* Chain multiple */
transform:rotate(45deg)scale(1.5);
transform-origin:top left;
}
CSS Animations
Define keyframes and apply them to create self-running animations.
@keyframesbounce {
0% {
transform:translateY(0);
}
50% {
transform:translateY(-30px);
}
100% {
transform:translateY(0);
}
}
.ball {
animation-name:bounce;
animation-duration:1s;
animation-timing-function:ease-in-out;
animation-delay:0.5s;
animation-iteration-count:infinite;
animation-direction:alternate;
animation-fill-mode:both;
/* Shorthand */
animation:bounce1sease-in-outinfinite;
}
04 — Responsive Design
Media Queries
Apply different CSS rules based on viewport size, orientation, or device
characteristics.
/* 1. Mobile-First Approach (Base styles are for mobile) */.responsive-card {
padding: 1rem;
display: block;
/* Stack on small screens */
}
/* 2. Scale Up (Tablet: 768px+) */@media(
min-width: 768px) {
.responsive-card {
padding: 2rem;
display: flex;
/* Side-by-side on larger screens */
}
}
/* 3. Range Media Queries (Modern Syntax!) */@media(1024px
<= width <=1440px) {
/* Only applies between 1024px and 1440px */
}
/* 4. Accessibility & System Preferences */@media(
prefers-color-scheme: dark) {
body {
background: #121212;
color: #fff;
}
}
@media(
prefers-reduced-motion: reduce) {
* {
animation-duration: 0.01ms!important;
}
/* Kill animations instantly */
}
Responsive Units
Use fluid units instead of fixed pixels for responsive layouts.
CSS Units Cheat Sheet:
-
📏 Absolute Pixel (
px)A fixed size unit representing physical screen pixels.1px = 1/96th inch. Does not respond to browser-level font-size configurations. Great for strict thin borders or shadow offsets. -
🌱 Root-Relative Em (
rem)Relative to the font-size of the root<html>element (usually default is16px, meaning1rem = 16px). Strongly recommended for margins, padding, and text to guarantee accessibility when users change browser-level zoom/text preferences. -
🌳 Element-Relative Em (
em)Relative to the activefont-sizeof the element itself (or its parent). If an element hasfont-size: 20px, then2em = 40px. Perfect for responsive components where margins/padding scale proportionately with the font. -
🖥 Viewport Width & Height (
vw/vh)Percentage of the user's viewport width or height.100vwis exactly 100% of browser window width, and100vhis 100% of height. Ideal for full-screen cover sections. -
📊 Percentage (
%)Relative directly to the sizing parameters of the immediate parent element, creating strict nesting layout flows.
/* 1. Viewport Units (Relative to screen size) */.hero-section {
width: 100vw;
/* 100% of viewport width */
height: 100vh;
/* 100% of viewport height */
height: 100dvh;
/* Dynamic VH (accounts for mobile URL bars!) */
min-width: 50vmin;
/* 50% of the smaller dimension (vw or vh) */
}
/* 2. Relative Typography & Spacing (Accessibility) */.typography-wrapper {
font-size: 1rem;
/* Relative to HTML root size (usually 16px) */
padding: 1.5em;
/* Relative to current element's font-size */
max-width: 65ch;
/* 'ch' = width of the '0' character (perfect reading length) */
}
/* 3. Fluid Responsive Calculations */.fluid-text {
/* clamp(MINIMUM, IDEAL (scales with viewport), MAXIMUM) */
font-size: clamp(1.2rem, 4vw, 2.5rem);
padding: clamp(1rem, 5vw, 4rem);
}
05 — Gradients & Shadows
Gradients
CSS supports linear, radial, and conic gradients as background images.
/* Linear gradient */
background:linear-gradient(135deg,#667eea,#764ba2);
background:linear-gradient(to
right,red,blue50%,green);
/* Radial gradient */
background:radial-gradient(circleatcenter,#f093fb,#f5576c);
background:radial-gradient(ellipse80%50%at50%,#f00,#00f);
/* Conic gradient (CSS4) */
background:conic-gradient(from0deg,red,yellow,green,blue,red);
/* Repeating */
background:repeating-linear-gradient(45deg,#0000,#00010px,#fff10px,#fff20px);
Box & Text Shadow
Add depth, elevation, and glow effects with CSS shadows.
/* box-shadow: x y blur spread color */
box-shadow:04px6pxrgba(0,0,0,.1);
box-shadow:inset02px4px#000;
/* inset */
/* Glow effect */
box-shadow:0020px#00e5ff;
/* Multiple shadows */
box-shadow:01px3pxrgba(0,0,0,.12),04px6pxrgba(0,0,0,.1),024px64pxrgba(0,0,0,.15);
/* text-shadow: x y blur color */
text-shadow:0010px#ff4081;
01 — CSS Custom Properties
CSS Variables (Custom Properties) MODERN
Define reusable values in :root and use them throughout your stylesheet. They cascade
and can be changed with JavaScript.
/* Define in :root (global scope) */:root {
--color-primary:#00e5ff;
--color-bg:#0b0c10;
--spacing-md:1rem;
--radius:8px;
--shadow:04px20pxrgba(0,0,0,.3);
}
/* Use with var() */.card {
background:var(
--color-bg);
color:var(
--color-primary);
border-radius:var(
--radius);
/* With fallback value */
padding:var(
--spacing-md,16px);
}
/* Override in component scope */.card--dark {
--color-primary:#ff4081;
}
/* Change via JavaScript */
// el.style.setProperty('--color-primary', '#ff0');
/* Computed with calc() */
--size:16px;
font-size:calc(var(
--size) *1.5);
02 — Advanced Selectors & At-Rules
At-Rules Reference
Special CSS instructions that start with @ symbol.
/* 1. Feature Queries (Conditional support logic) */@supports(
display: grid) {
.layout {
display: grid;
}
}
@supports not(
clip-path: polygon(0 0)) {
.layout {
/* Fallback */
}
}
/* 2. Animations (Keyframes) */@keyframesslideIn {
0% {
transform: translateX(-100%);
}
100% {
transform: translateX(0);
}
}
/* 3. Custom Fonts */@font-face {
font-family: 'MyBrandFont';
src: url('font.woff2') format('woff2');
font-display: swap;
/* Performance */
}
/* 4. Cascade Layers (Architecture) */@layerreset, framework, custom; @layercustom {
.btn {
background: blue;
}
/* Always wins against framework! */
}
/* 5. Typed Custom Properties (Houdini) */@property
--hue-angle {
syntax: '< angle> ';
initial-value: 0deg;
inherits: false;
}
CSS Functions
Powerful built-in functions for calculations, transformations, and more.
/* 1. Math Functions */.element {
width: calc(100%- 2rem);
/* Mixed unit calculation */
font-size: clamp(1rem, 3vw, 2rem);
/* Responsive limits */
width: min(500px, 100%);
/* Responsive max-width equivalent */
width: max(300px, 50%);
/* Responsive min-width equivalent */
width: round(down, var(
--w), 50px);
/* Step rounding */
}
/* 2. Color Functions */.theme {
color: color-mix(in srgb,
red50%, blue);
/* Mixes to purple */
background: oklch(0.70.15250);
/* Perceptually uniform color space */
}
/* 3. Environment Variables (e.g. mobile notch avoidance) */body {
padding-top: env(safe-area-inset-top);
padding-bottom: env(safe-area-inset-bottom);
}
03 — Visual Effects
Clip Path & Masks
Clip elements to geometric or SVG shapes for creative layouts.
/* Basic shapes */
clip-path:circle(50%);
clip-path:ellipse(60%40%);
clip-path:inset(10px20pxround8px);
/* Polygon */
clip-path:polygon(50%0,100%100%,0100%);
/* Diagonal cut */
clip-path:polygon(00,100%0,100%85%,0100%);
/* Path (SVG) */
clip-path:path('M 0 0 ...');
/* Mask */
mask-image:linear-gradient(to
bottom,#000,transparent);
-webkit-mask-image:url('mask.svg');
CSS Scroll Snapping MODERN
Create premium, mobile-app-like horizontal sliders or full-page vertical scroll
sections with pure CSS.
Scroll Containers vs Children:
- Container: Needs
scroll-snap-type: [axis] [strictness](e.g.x mandatory). - Child items: Needs
scroll-snap-align: [alignment](e.g.centerorstart).
/* 1. Scroll Snap Parent Container */.slider-container {
display: flex;
overflow-x: auto;
/* Snap horizontally, locking strictly onto items */
scroll-snap-type: x mandatory;
/* Enable premium inertial momentum scrolling on iOS */
-webkit-overflow-scrolling: touch;
}
/* 2. Scroll Snap Children */.slider-slide {
flex: 00100%;
/* full width cards */
/* Snap each card perfectly into the viewport center */
scroll-snap-align: center;
scroll-snap-stop: always;
/* stop swipe passing card */
}
Aspect Ratio & Object Fit ESSENTIAL
Maintain precise element box ratios and control how images or videos scale and crop
inside containers.
Sizing Strategies:
- aspect-ratio: Lock width/height relative to each other (e.g.
16 / 9or1for squares). - object-fit: cover: Cropped to fill, preserving proportions. object-fit: contain: Fully visible, padded.
.responsive-media-container {
/* Automatically keep container locked at 16:9 ratio */
aspect-ratio: 16/ 9;
width: 100%;
overflow: hidden;
}
.responsive-media-container img {
width: 100%;
height: 100%;
/* Prevent image stretching: auto crops like background-size: cover */
object-fit: cover;
object-position: center top;
}
CSS Filters
Apply visual filter effects like blur, brightness, and contrast.
.img {
filter:blur(4px);
filter:brightness(1.5);
filter:contrast(200%);
filter:grayscale(100%);
filter:hue-rotate(90deg);
filter:invert(100%);
filter:opacity(0.5);
filter:saturate(200%);
filter:sepia(50%);
filter:drop-shadow(2px2px8px#ff4081);
/* Combine multiple */
filter:brightness(1.2)saturate(150%);
}
/* Backdrop filter (frosted glass) */.glass {
backdrop-filter:blur(10px)brightness(1.1);
background:rgba(255,255,255,0.1);
}
3D Transforms & Perspective
Create 3D effects with perspective and 3D transform functions.
.scene {
perspective:800px;
/* 3D depth context */
}
.card-3d {
transform-style:preserve-3d;
transform:rotateY(30deg)rotateX(15deg);
}
.card-3d:hover {
transform:rotateY(180deg);
/* flip */
}
.card-back {
backface-visibility:hidden;
transform:rotateY(180deg);
}
/* translateZ = push toward viewer */
transform:translateZ(50px);
Blend Modes & Compositing
Control how elements blend with backgrounds (like Photoshop blend modes).
/* mix-blend-mode: applies to element */.text-overlay {
mix-blend-mode:multiply;
mix-blend-mode:screen;
mix-blend-mode:overlay;
mix-blend-mode:difference;
/* invert effect */
mix-blend-mode:color-dodge;
mix-blend-mode:luminosity;
}
/* background-blend-mode: bg layers */.hero {
background:url('img.jpg'),#ff4081;
background-blend-mode:multiply;
}
/* Isolation: create stacking context */
isolation:isolate;
04 — Modern Layout & CSS Logic
Logical Properties NEW
Writing-mode aware properties that work for RTL/LTR and vertical text.
/* 1. Dimensions */.box {
inline-size: 200px;
/* width in LTR/RTL, height in vertical */
block-size: 100px;
/* height in LTR/RTL, width in vertical */
}
/* 2. Margins & Padding */.spacing {
margin-inline-start: 10px;
/* margin-left in LTR, margin-right in RTL */
margin-inline-end: 20px;
/* margin-right in LTR, margin-left in RTL */
padding-block-start: 15px;
/* padding-top */
/* Shorthands */
margin-inline: auto;
/* Centers block: margin-left & right auto */
padding-block: 2rem;
/* padding-top & bottom */
}
/* 3. Borders & Positioning */.border-pos {
border-inline-start: 4pxsolid blue;
/* Dynamic left/right border */
inset: 0;
/* top/right/bottom/left: 0 */
inset-inline: 10px;
/* left/right: 10px */
}
CSS Containment & Performance
Optimize rendering performance by limiting what the browser recalculates.
.performance-card {
/* 1. Isolation Containment (Performance Booster!) */
contain: content;
/* layout + paint: isolates this element completely */
contain: paint;
/* prevents painting children outside boundaries */
contain: layout;
/* browser ignores this subtree when computing global layout reflows */
contain: strict;
/* layout + paint + size + style: absolute isolation */
/* 2. On-Demand Rendering (Lazy Loading for DOM elements) */
content-visibility: auto;
/* browser skips painting/rendering when off-screen! */
contain-intrinsic-size: auto350px;
/* reserves placeholder height to avoid scrollbar jumping */
/* 3. GPU/Hardware Acceleration Hints */
will-change: transform, opacity;
/* prompts browser to render on GPU ahead of time */
will-change: auto;
/* default (reset to clean up browser memory) */
}
Container Queries CSS4
Style elements based on their container's size, not the viewport. A game-changer for
components.
/* 1. Establish the Container Context (Required!) */.widget-wrapper {
container-type: inline-size;
/* Tells browser to monitor width */
container-name: widget;
/* Optional naming for specific targeting */
}
/* 2. Base Component Styles (Default mobile-layout) */.widget-card {
display: block;
/* Stacked */
}
/* 3. Container Query (Component responds to its OWN wrapper, not viewport!)
*/@containerwidget(
min-width: 400px) {
.widget-card {
display: flex;
/* Shift to side-by-side if wrapper has room! */
gap: 20px;
}
}
/* 4. Dynamic Container Units (cqw = % of container width) */.widget-title {
font-size: clamp(1rem, 5cqw, 2rem);
/* Fluid text based on container! */
}
CSS Tricks & Recipes
Glassmorphism Card
Frosted glass effect using backdrop-filter. Works over colorful backgrounds.
.glass {
background:rgba(255,255,255,0.1);
backdrop-filter:blur(12px)saturate(180%);
-webkit-backdrop-filter:blur(12px);
border:1pxsolidrgba(255,255,255,0.2);
border-radius:16px;
box-shadow:08px32pxrgba(31,38,135,0.37);
color:#fff;
}
Pure CSS Accordion (FAQ Box)
Interactive, keyboard-accessible collapsible FAQ blocks using pure HTML/CSS without a
single line of JavaScript.
/* HTML structure: < details class="faq-card"> < summary class="faq-title">
Question?< /summary> < div class="faq-content"> Answer here...< /div> <
/details> */.faq-card {
background: var(--surface);
border: 1pxsolidvar(--border);
border-radius: 8px;
margin-bottom: 1rem;
overflow: hidden;
}
.faq-title {
padding: 1rem;
font-weight: 600;
cursor: pointer;
/* Premium arrow transitions when details tag opens */
list-style: none;
}
.faq-card[open] .faq-title {
border-bottom: 1pxsolidvar(--border);
}
.faq-content {
padding: 1rem;
line-height: 1.6;
}
Animated Gradient Border
Conic gradient animated border using a pseudo-element trick.
@property
--angle {
syntax:'< angle> ';
inherits:false;
initial-value:0deg;
}
.glow-border {
border:3pxsolidtransparent;
background-image:linear-gradient(#1a1a2e,#1a1a2e),conic-gradient(fromvar(
--angle),#f00,#ff0,#0f0,#00f,#f00);
background-clip:padding-box,border-box;
background-origin:border-box;
animation:rotate3slinearinfinite;
}
@keyframesrotate {
to {
--angle:360deg;
}
}
Truncate Text (Single & Multi-line)
Show ellipsis for overflow text, works for single or multiple lines.
/* 1. Classic Single-Line Truncation (Requires all 3 properties) */.truncate-single {
white-space: nowrap;
/* Prevent wrapping */
overflow: hidden;
/* Hide overflow */
text-overflow: ellipsis;
/* Add "..." */
}
/* 2. Modern Multi-Line Clamp (e.g., Blog Post previews) */.truncate-multi {
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 3;
/* Show exactly 3 lines, then add "..." */
overflow: hidden;
}
Gradient Text Effect
Apply gradient colors to text using background-clip: text.
/* 1. Paint the Gradient on the Background */.premium-gradient {
background: linear-gradient(90deg, #FF6C36, #7c3aed, #00e5ff);
/* 2. Clip the Background exactly to the Text Shape */
background-clip: text;
-webkit-background-clip: text;
/* Vendor prefix required for Safari */
/* 3. Make the actual text invisible so the background shows through! */
color: transparent;
-webkit-text-fill-color: transparent;
/* Optional: Animation for a shimmering effect */
background-size: 300%;
animation: shimmer4slinearinfinite;
}
@keyframesshimmer {
0% {
background-position: 0%center;
}
100% {
background-position: -300%center;
}
}
Pure CSS Dark Mode Toggle
Implement dark mode using CSS custom properties and the prefers-color-scheme media
query.
/* Light mode defaults */:root {
--bg:#ffffff;
--text:#111111;
--card-bg:#f0f0f0;
}
/* Auto dark mode */@media(
prefers-color-scheme:dark) {
:root {
--bg:#0b0c10;
--text:#e8eaf6;
--card-bg:#13141a;
}
}
/* Manual toggle with data attribute */[data-theme="dark"] {
--bg:#0b0c10;
--text:#e8eaf6;
}
/* JS: document.documentElement */
// .dataset.theme = 'dark'; */
Perfect Centering Recipes
Multiple ways to center elements — from old-school to modern.
/* 1. Flexbox (recommended) */.center {
display:flex;
align-items:center;
justify-content:center;
}
/* 2. Grid (one line!) */.center {
display:grid;
place-items:center;
}
/* 3. Absolute + transform */.center {
position:absolute;
top:50%;
left:50%;
transform:translate(-50%,-50%);
}
/* 4. Margin auto (block elements) */.center {
width:500px;
margin:0auto;
}
CSS-Only Tooltip
Build accessible tooltips using only CSS with data attributes and ::after.
[data-tooltip] {
position:relative;
}
[data-tooltip]::after {
content:attr(data-tooltip);
/* from HTML attr */
position:absolute;
bottom:calc(100%+8px);
left:50%;
transform:translateX(-50%);
background:#111;
color:#fff;
padding:4px10px;
border-radius:4px;
white-space:nowrap;
font-size:0.75rem;
opacity:0;
pointer-events:none;
transition:opacity0.2s;
}
[data-tooltip]:hover::after {
opacity:1;
}
Smooth Scroll & Scroll-Driven Animations
Native smooth scrolling and linking scroll position to CSS animations.
/* Smooth scroll globally */html {
scroll-behavior:smooth;
}
/* Scroll margin for sticky nav */section {
scroll-margin-top:80px;
}
/* Scroll-driven animation (CSS4!) */@keyframesreveal {
from {
opacity:0;
transform:translateY(40px);
}
to {
opacity:1;
transform:translateY(0);
}
}
.fade-in {
animation:reveallinearboth;
animation-timeline:view();
/* tied to scroll! */
animation-range:entry0%cover30%;
}
/* Progress bar tied to page scroll */.progress {
animation:scaleXlinear;
animation-timeline:scroll();
transform-origin:left;
}
CSS-Only Loading Spinners
Three types of pure CSS loading spinners without any images.
/* Spinning border */.spinner {
width:40px;
height:40px;
border:4pxsolidrgba(0,0,0,.1);
border-top-color:#3498db;
border-radius:50%;
animation:spin0.8slinearinfinite;
}
@keyframesspin {
to {
transform:rotate(360deg);
}
}
/* Pulsing dot */.pulse {
animation:pulse1.5sease-in-outinfinite;
}
@keyframespulse {
0%,100% {
transform:scale(1);
opacity:1;
}
50% {
transform:scale(1.5);
opacity:0.5;
}
}
Hover Card Flip Effect
3D card flip on hover using transform-style: preserve-3d and backface-visibility.
.flip-card {
perspective:1000px;
width:200px;
height:120px;
}
.flip-card-inner {
position:relative;
width:100%;
height:100%;
transform-style:preserve-3d;
transition:transform0.6s;
}
.flip-card:hover .flip-card-inner {
transform:rotateY(180deg);
}
.flip-front, .flip-back {
position:absolute;
width:100%;
height:100%;
backface-visibility:hidden;
border-radius:8px;
}
.flip-back {
transform:rotateY(180deg);
}