Chapter 02 · HTML, CSS, JS, React, Node
CSS3 & Modern Styling Architecture
16 topics · 3 sections · beginner-friendly study notes · Updated
CSS controls presentation.
This chapter covers selectors and specificity, the box model, units, positioning and stacking, Flexbox and Grid layouts, responsive media queries, custom properties for theming, and transitions, animations and transforms.
Layout and specificity bugs are the most common front-end problems and a staple interview topic.
Every website - navigation bars, card grids, dashboards, themes, micro-interactions and mobile-first designs.
CSS Selectors Hierarchy
Selectors choose which elements a rule styles. They range from simple (type p, class .card, id #hero, universal *, attribute [type="email"]) to combinators (descendant , child >, adjacent +, general sibling ~) and pseudo-classes/elements (:hover, :nth-child(), ::before).
In short: A selector is an address that says which elements get the style.
Think about it
Selecting precisely without over-coupling to markup is the core CSS skill and a common test question.
Combinators describe relationships in the DOM tree: nav a matches any link inside nav; nav > a only direct children; h2 + p the paragraph right after an h2; h2 ~ p all later sibling paragraphs.
Pseudo-classes select by state or position (:focus-visible, :not(), :is(), :has() - the parent selector, :first-child), pseudo-elements create or target virtual parts (::before, ::after, ::placeholder, ::selection).
Selectors are matched right-to-left by the browser, so overly deep chains are both brittle and slower.
Prefer flat class-based selectors (BEM style) over long descendant chains.
Key points
- Combinator: Symbol describing the relationship between two selectors.
- Pseudo-class: Selects an element in a given state or position (:hover, :nth-child).
- Pseudo-element: Targets a generated or partial part of an element (::before, ::first-line).
Example
CodeSelector types and combinators:
*, *::before, *::after { box-sizing: border-box; }
p { line-height: 1.6; } /* type */
.card { padding: 1rem; } /* class */
#hero { min-height: 60vh; } /* id */
input[type="email"] { border-color: teal; } /* attribute */
nav a { text-decoration: none; } /* descendant */
ul > li { list-style: square; } /* child */
h2 + p { font-weight: 600; } /* adjacent sibling */
li:nth-child(odd) { background: #f5f5f5; }
a:not(.btn):hover { text-decoration: underline; }
.card:has(img) { display: grid; } /* parent selector */
.quote::before { content: "\201C"; }CSS Specificity Calculation
The cascade resolves conflicting declarations by origin and importance, then specificity, then source order. Specificity is counted as (inline, ids, classes/attributes/pseudo-classes, elements/pseudo-elements) and compared left to right.
In short: More specific selector wins; if tied, the later rule wins.
Think about it
Predicting which colour wins is a guaranteed exam question and the root of most "my CSS is not applied" bugs.
Examples
p = (0,0,0,1); `.
note = (0,0,1,0); #hero = (0,1,0,0); #hero .
note p` = (0,1,1,1).
Inline style beats all selectors; `!
important` beats normal declarations (avoid it).
The universal selector and combinators add 0.
:where() contributes zero; :is() and :not() take their most specific argument.
Tuples are not base-10 numbers: eleven classes still lose to one id.
Inheritance gives the weakest value of all - a directly targeted rule always beats an inherited one.
Cascade layers (@layer) let you order whole groups of styles regardless of specificity.
Keep specificity low and flat (BEM, utility classes, CSS Modules).
Key points
- Specificity: Weight of a selector used to resolve conflicts.
- Inheritance: Children take computed values for inheritable properties (color, font) from parents.
- @layer: Cascade layers: later layers win over earlier ones regardless of specificity.
Read more
Example
CodeSpecificity comparison:
p { color: black; } /* 0,0,0,1 */
.note { color: blue; } /* 0,0,1,0 */
#hero p { color: green; } /* 0,1,0,1 */
p.note:hover { color: red; } /* 0,0,2,1 */
/* <p id="x" class="note"> inside #hero -> green wins over blue and black */
:where(.btn) { color: gray; } /* 0,0,0,0 - easy to override */
@layer base, components;
@layer base { a { color: navy; } }
@layer components { .link { color: crimson; } }The CSS Box Model
Every element is a box made of content, padding, border and margin (inside to outside). `box-sizing: content-box (default) makes width apply to content only; border-box` includes padding and border in width.
In short: Content is wrapped by padding, then border, then margin.
Think about it
Width/height arithmetic questions appear in every viva and explain unexpected overflow.
With content-box, width:200px; padding:20px; border:5px gives a rendered width of 250px.
With border-box it stays 200px.
Vertical margins of adjacent block siblings collapse to the larger one (margins of floats, flex and grid items do not collapse).
Padding sits inside the background; margin is transparent space outside.
Negative margins pull elements.
outline does not take layout space.
Most modern resets use `*, *::before, *::after { box-sizing: border-box; }`.
Logical properties (margin-inline, padding-block) adapt to writing direction.
Key points
- Margin collapsing: Adjacent vertical margins merge into the larger value.
- border-box: width includes content + padding + border.
- Outline: Drawn outside the border and takes no layout space.
Read more
Example
CodeBox model reset and card:
*, *::before, *::after { box-sizing: border-box; }
.card {
width: 300px;
padding: 16px;
border: 2px solid #ccc;
margin: 24px auto; /* horizontally centred */
}
/* content-box: 300 + 32 + 4 = 336px rendered. border-box: 300px. */CSS Sizing Units
CSS lengths are absolute (px, cm, pt) or relative: % (of the parent), em (own/parent font size), rem (root font size), vw/vh (viewport), dvh, ch, fr (grid), plus functions calc(), min(), max() and clamp().
In short: Use rem for text and spacing, % or fr for layouts, px for hairlines and borders.
Think about it
Correct units make layouts scale across devices and honour accessibility settings.
em compounds when nested (1.2em inside 1.2em = 1.44x) while rem always refers to the root font size, which respects the user browser setting - so rem scales with user preferences.
% width is relative to the containing block width; % height needs a parent with explicit height.
100vh on mobile includes the browser bars, so 100dvh (dynamic viewport) is more reliable.
clamp(min, preferred, max) gives fluid sizing without media queries.
ch equals the width of the digit 0 - ideal for readable measure (max-width: 65ch).
min-content, max-content and fit-content size by content.
Avoid px for font sizes because it can ignore user zoom settings.
Key points
- rem: Relative to the root (html) font size.
- em: Relative to the element font size (parent for font-size).
clamp(): Value constrained between a minimum and maximum around a preferred size.- dvh: Dynamic viewport height that accounts for mobile browser UI.
Example
CodeChoosing units:
html { font-size: 100%; } /* 16px by default */
body { font-size: 1rem; line-height: 1.6; }
h1 { font-size: clamp(1.75rem, 1.2rem + 2.5vw, 3rem); }
.container { width: min(100% - 2rem, 70rem); margin-inline: auto; }
.prose { max-width: 65ch; }
.hero { min-height: 100dvh; }
.sidebar { width: calc(25% - 1rem); }
.btn { padding: 0.5em 1em; } /* scales with the button font size */
.divider { border-top: 1px solid #ddd; } /* px for hairlines */Display Modes & Visibility
The display property sets an element outer and inner layout type: block, inline, inline-block, flex, grid, none, contents. visibility and opacity hide elements without (or partially) removing them from layout.
In short: display decides how a box lays out; display:none removes it, visibility:hidden only hides it.
Think about it
Knowing the difference between none, hidden and opacity:0 is a classic interview question.
Block elements fill the available width and start on a new line; inline elements ignore width/height and vertical margins; inline-block flows inline but accepts width/height.
display:none removes the element from layout and the accessibility tree.
visibility:hidden keeps the space but hides it (still occupies layout, hidden from assistive tech).
opacity:0 keeps space and stays clickable and focusable.
The hidden attribute applies display:none.
display:contents removes the box but keeps children.
For screen-reader-only text use a visually-hidden utility (clip and 1px size) rather than display:none.
Whitespace between inline-block elements creates small gaps.
Key points
- Block / inline / inline-block: Block: full width on new line. Inline: flows in text. Inline-block: inline flow with box sizing.
- display:none: Removes the element from layout and accessibility tree.
- visibility:hidden: Invisible but still occupies space.
Read more
Example
CodeDisplay and hiding techniques:
.hide-layout { display: none; } /* gone: no space, no a11y */
.hide-keep { visibility: hidden; } /* invisible, space kept */
.fade { opacity: 0; pointer-events: none; transition: opacity .2s; }
.badge { display: inline-block; padding: 2px 8px; }
.flex-row { display: flex; gap: 8px; }
.sr-only {
position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px;
overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; border: 0;
}CSS Positioning Schemes
The position property has five values: static (normal flow, default), relative (offset from its normal place, still occupying space), absolute (removed from flow, placed relative to the nearest positioned ancestor), fixed (relative to the viewport) and sticky (relative until a scroll threshold, then fixed).
In short: relative nudges, absolute pins to a positioned parent, fixed pins to the screen, sticky sticks while scrolling.
Think about it
Used for headers, modals, tooltips and badges; positioning bugs are very common.
An absolutely positioned element needs a positioned ancestor (position:relative is the usual way) or it positions against the initial containing block.
Absolute and fixed elements leave a hole in flow and shrink-wrap to content unless sized.
top/right/bottom/left have no effect on static.
sticky requires a threshold such as top:0 and fails if an ancestor has overflow:hidden/auto without a scroll container context.
inset: 0 is shorthand for all four offsets.
Transforms and filters on an ancestor change the containing block for fixed elements.
Prefer Flexbox and Grid for layout and use positioning for overlays, badges and sticky headers.
Key points
Read more
Example
CodeCommon positioning patterns:
.card { position: relative; }
.card .badge { position: absolute; top: 8px; right: 8px; }
.navbar { position: sticky; top: 0; background: white; z-index: 10; }
.fab { position: fixed; right: 16px; bottom: 16px; }
.overlay { position: fixed; inset: 0; background: rgb(0 0 0 / .5); }
.nudge { position: relative; left: 10px; top: -4px; } /* still occupies original space */Z-Index & Stacking Context
z-index controls the stacking order of positioned elements (and flex/grid items) along the z-axis. A stacking context is an isolated three-dimensional group in which z-index values are compared only among siblings inside that group.
In short: A higher z-index only wins against elements in the same stacking context.
Think about it
The famous "my modal is behind the header even with z-index 9999" bug is a stacking-context problem.
Stacking contexts are created by the root element, position (relative/absolute/fixed/sticky) with a z-index other than auto, opacity < 1, transform, `filter, isolation: isolate, will-change`, and flex/grid items with z-index.
A child with z-index: 9999 inside a parent context of z-index: 1 still cannot appear above a sibling context at z-index: 2.
Paint order within a context: background, negative z-index, in-flow block, floats, inline content, z-index auto/0, positive z-index.
Use a small, documented scale (10, 20, 30...
) via custom properties and isolation:isolate on components to contain their layers.
Key points
Example
CodeStacking context trap and fix:
.header { position: relative; z-index: 2; }
.content { position: relative; z-index: 1; }
/* A modal inside .content with z-index:9999 still sits UNDER .header */
.card { isolation: isolate; } /* keeps child z-indexes local */
:root { --z-dropdown: 10; --z-sticky: 20; --z-modal: 30; --z-toast: 40; }
.modal { position: fixed; inset: 0; z-index: var(--z-modal); }
/* Fix: render modal at the end of <body> (portal) so it is not trapped */CSS Flexbox Layout
Flexbox lays out items in one dimension. A flex container (`display:flex) has a main axis (flex-direction) and a cross axis. justify-content aligns along the main axis; align-items along the cross axis; flex-wrap allows multiple lines; gap` adds spacing.
In short: Put items in a row or column and control the space between them.
Think about it
Centring with Flexbox is the classic "how do you centre a div" question.
The default direction is row.
When flex-direction: column, the main axis becomes vertical so justify-content works vertically.
align-content distributes lines when items wrap.
place-content/place-items are shorthands.
Use Flexbox for components (nav bars, toolbars, button groups, centring) where content drives size; use Grid for page-level two-dimensional layouts.
margin: auto on a flex item absorbs free space (pushing it to the end).
Flex containers establish a flex formatting context, and margins of children do not collapse.
Key points
- Main axis: Direction of flex-direction (row = horizontal).
- Cross axis: Perpendicular to the main axis.
- gap: Spacing between flex/grid items without margin hacks.
Read more
Example
CodeFlexbox patterns:
.navbar {
display: flex;
justify-content: space-between;
align-items: center;
gap: 16px;
}
.center {
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
}
.tags { display: flex; flex-wrap: wrap; gap: 8px; }
.nav-spacer { margin-left: auto; } /* push last items to the far end */Flex Item Mechanics
Flex items distribute space using flex-grow, flex-shrink and flex-basis (shorthand flex). Basis is the starting size, grow shares leftover space, shrink removes overflow proportionally. align-self and order adjust individual items.
In short: flex: 1 means "take an equal share of the free space".
Think about it
Sidebar-plus-content layouts and overflow bugs depend on grow, shrink, basis and min-width.
flex: 1 expands to 1 1 0% (grow 1, shrink 1, basis 0), so items split the container equally regardless of content.
flex: auto is 1 1 auto (basis from content/width).
flex: none is 0 0 auto (rigid).
Free space = container size - sum of bases; each item grows by free * grow / totalGrow.
When content overflows, shrink is weighted by shrink * basis.
Flex items have min-width: auto, so long text or images prevent shrinking - fix with min-width: 0 (very common bug for text ellipsis).
order changes visual order only, not DOM or tab order, which can harm accessibility.
align-self overrides the container align-items for one item.
Key points
- flex-basis: Initial main size of an item before growing/shrinking.
- flex-grow: Share of leftover space an item receives.
- flex-shrink: How much an item shrinks when space is lacking.
- min-width: 0: Allows a flex item to shrink below its content size.
Read more
Example
CodeGrow, shrink and basis:
.layout { display: flex; gap: 16px; }
.sidebar { flex: 0 0 240px; } /* fixed 240px */
.content { flex: 1; min-width: 0; } /* fills remaining space, can shrink */
.row { display: flex; }
.row .a { flex: 1; } /* 1 part */
.row .b { flex: 2; } /* 2 parts: twice as wide as .a */
.row .c { align-self: flex-end; order: -1; }
.truncate { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }CSS Grid 2D Layout
Grid is a two-dimensional layout system. `display:grid with grid-template-columns/rows defines tracks; the fr` unit takes a fraction of free space; items are placed by line numbers, spans or names.
In short: Rows and columns at the same time.
Think about it
Modern layout questions expect Grid knowledge and the Flex-vs-Grid distinction.
repeat(auto-fit, minmax(220px, 1fr)) creates a responsive card grid with no media queries: auto-fit collapses empty tracks, auto-fill keeps them.
Items span tracks with grid-column: 1 / -1 or span 2.
`gap` spaces tracks.
Implicit tracks are sized by grid-auto-rows/grid-auto-flow (use dense to back-fill holes).
minmax(min, max) bounds track size.
Alignment uses justify-items, align-items and place-items.
Subgrid lets children share parent tracks.
Combine with Flexbox: Grid for page and card grids, Flexbox inside components.
Key points
- fr unit: Fraction of the available space in the grid container.
- Track: A single row or column in the grid.
- auto-fit vs auto-fill: auto-fit collapses empty tracks; auto-fill keeps them as empty space.
Example
CodeGrid layouts:
.cards {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
gap: 20px;
}
.gallery { display: grid; grid-template-columns: repeat(3, 1fr); grid-auto-rows: 160px; gap: 8px; }
.gallery .wide { grid-column: span 2; }
.gallery .tall { grid-row: span 2; }
.full { grid-column: 1 / -1; }
.center { display: grid; place-items: center; min-height: 100vh; }Grid Areas & Holy Grail Layout
grid-template-areas names regions of the grid in an ASCII-art style and grid-area assigns elements to them. The Holy Grail layout is header, footer, a main column and two side columns where the content stays centred and columns are equal height.
In short: Draw the page layout with names, then drop each element into its name.
Think about it
Holy Grail is the canonical layout interview question and shows Grid advantage over older techniques.
Each row string lists one name per column; repeated names merge into a rectangle (areas must be rectangular, a dot `.
` means an empty cell).
The Holy Grail used to need floats and negative margins; with Grid it is a few lines: grid-template-columns: 200px 1fr 200px; grid-template-rows: auto 1fr auto; min-height: 100vh, so the footer sticks to the bottom and the middle row stretches.
Responsive variants redefine grid-template-areas inside a media query (stack areas on mobile).
Keep DOM order logical for accessibility and reorder visually with areas only when the reading order stays sensible.
Key points
Read more
Example
CodeHoly Grail with Grid areas:
.page {
display: grid;
min-height: 100vh;
grid-template-columns: 200px 1fr 200px;
grid-template-rows: auto 1fr auto;
grid-template-areas:
"header header header"
"nav main aside"
"footer footer footer";
gap: 16px;
}
.page > header { grid-area: header; }
.page > nav { grid-area: nav; }
.page > main { grid-area: main; }
.page > aside { grid-area: aside; }
.page > footer { grid-area: footer; }
@media (max-width: 700px) {
.page {
grid-template-columns: 1fr;
grid-template-areas: "header" "nav" "main" "aside" "footer";
}
}Responsive Media Queries
Responsive design adapts layout to screen size using fluid units (%, rem, vw), flexible images (max-width:100%) and @media queries. Mobile-first writes base styles for small screens and adds min-width queries for larger ones.
In short: One site that works on phone, tablet and desktop.
Think about it
Mobile-first is the expected modern approach; most traffic is mobile.
Always include the viewport meta tag.
Prefer relative units (rem for type, % or fr for layout).
Typical breakpoints: 640px, 768px, 1024px, but choose them where the content breaks, not for specific devices.
Queries can test min-width, max-width, orientation, prefers-color-scheme, prefers-reduced-motion, hover, pointer and print.
Range syntax: @media (width >= 768px).
Container queries (@container) let components respond to their parent size, which suits reusable cards.
`clamp(1rem, 2.5vw, 2rem)` gives fluid typography.
Key points
- Mobile-first: Base CSS for small screens; min-width queries add enhancements.
- Breakpoint: Viewport width where the layout changes.
- prefers-reduced-motion: Media feature indicating the user wants less animation.
Read more
Example
CodeMobile-first breakpoints:
.grid { display: grid; grid-template-columns: 1fr; gap: 16px; }
@media (min-width: 768px) { .grid { grid-template-columns: repeat(2, 1fr); } }
@media (min-width: 1024px) { .grid { grid-template-columns: repeat(4, 1fr); } }
img { max-width: 100%; height: auto; }
@media (prefers-color-scheme: dark) { :root { color-scheme: dark; } }
@media (prefers-reduced-motion: reduce) { * { animation: none !important; transition: none !important; } }
@media (hover: hover) { .card:hover { transform: translateY(-4px); } }
.card-wrap { container-type: inline-size; }
@container (min-width: 400px) { .card { display: flex; } }CSS Variables & Themes
CSS custom properties (--name: value) are declared on any element, read with var(--name, fallback), inherit down the tree and can be changed at runtime. They enable design tokens and themes such as light/dark mode.
In short: Store a colour or size once and reuse it everywhere; change it in one place to retheme the site.
Think about it
Theming, design systems and dynamic UI without rebuilding CSS.
Declare tokens on :root for global scope; override them on [data-theme="dark"] or inside components for local scope.
Unlike Sass variables they exist at runtime, cascade and inherit, and can be changed from JavaScript with `element.
style.
setProperty("--x", "...
")`.
Use the fallback argument for safety.
@property registers typed custom properties so they can animate.
Combine prefers-color-scheme with a user toggle stored in localStorage.
Custom properties can hold any token list, such as --shadow or --space-2, and combine with calc().
Key points
Example
CodeTheme tokens with custom properties:
:root {
--bg: #ffffff;
--fg: #111827;
--accent: #2563eb;
--space: 1rem;
}
[data-theme="dark"] {
--bg: #0b1220;
--fg: #e5e7eb;
--accent: #60a5fa;
}
body { background: var(--bg); color: var(--fg); }
.btn { background: var(--accent); padding: calc(var(--space) / 2) var(--space); }
.note { color: var(--note-color, gray); } /* fallback */
/* JS: document.documentElement.dataset.theme = "dark";
el.style.setProperty("--accent", "#ef4444"); */CSS Transitions
Transitions animate a property change over time using transition-property, -duration, -timing-function and -delay (shorthand transition). They run when a property value changes, for example on :hover, :focus or when a class is toggled.
In short: Instead of snapping instantly, the change glides from the old value to the new one.
Think about it
Micro-interactions are expected in modern UIs and performance of animations is a common question.
Only properties with computable intermediate values can transition (not `display or auto` heights).
For smoothness animate transform and opacity - they run on the compositor and avoid layout/paint - rather than width, top or margin.
Timing functions: ease, linear, ease-in-out, cubic-bezier(), steps().
Define the transition on the base state so it also applies when returning.
transitionend events fire in JavaScript.
Respect `prefers-reduced-motion`.
A hidden-to-visible fade needs opacity plus `visibility or the newer @starting-style/transition-behavior: allow-discrete`.
Key points
Read more
Example
CodeHover and fade transitions:
.btn {
background: #2563eb;
transform: translateY(0);
transition: background-color .2s ease, transform .2s ease, box-shadow .2s ease;
}
.btn:hover, .btn:focus-visible {
background: #1d4ed8;
transform: translateY(-2px);
box-shadow: 0 6px 14px rgb(0 0 0 / .2);
}
.panel { opacity: 0; visibility: hidden; transition: opacity .25s, visibility 0s .25s; }
.panel.open { opacity: 1; visibility: visible; transition-delay: 0s; }Keyframe Animations
@keyframes defines intermediate steps of an animation (by percentage, or from/to), and the animation shorthand applies it with name, duration, timing function, delay, iteration count, direction, fill mode and play state.
In short: Write the steps of the movie with @keyframes, then play it on an element.
Think about it
Loaders, attention cues and onboarding effects rely on keyframes.
Unlike transitions, animations need no trigger, can loop (infinite), alternate, and have multiple steps.
animation-fill-mode: forwards keeps the final state; both also applies the first keyframe during the delay.
`animation-play-state: paused` pauses on hover.
Stagger with animation-delay or a custom property like --i.
Prefer animating transform/opacity.
Use steps() for sprite or typing effects.
will-change hints at upcoming changes but should be used sparingly.
Honour `prefers-reduced-motion` and avoid flashing more than three times per second (accessibility).
Scroll-driven animations (animation-timeline) are the modern extension.
Key points
- @keyframes: Defines the named sequence of animation steps.
- animation-fill-mode: Which styles apply before the start and after the end.
- animation-iteration-count: Number of repeats, or infinite.
Example
CodeSpinner, pulse and staggered entry:
@keyframes spin { to { transform: rotate(360deg); } }
@keyframes pulse { 0%, 100% { transform: scale(1); } 50% { transform: scale(1.08); } }
@keyframes slide-in {
from { opacity: 0; transform: translateY(16px); }
to { opacity: 1; transform: translateY(0); }
}
.spinner { animation: spin 1s linear infinite; }
.cta { animation: pulse 1.6s ease-in-out infinite; }
.item { animation: slide-in .4s ease-out both; animation-delay: calc(var(--i) * 80ms); }
.item:hover { animation-play-state: paused; }
@media (prefers-reduced-motion: reduce) { .spinner, .cta, .item { animation: none; } }CSS Transforms
The transform property moves, rotates, scales and skews an element without affecting normal layout flow: translate(), rotate(), scale(), skew() and 3D forms such as rotateY(), translateZ() and perspective(). Individual properties translate, rotate and scale are also available.
In short: Change how an element is drawn (move, spin, resize) without changing the layout around it.
Think about it
The cheap and smooth way to animate, and a base for hover effects, modals, carousels and flips.
Transforms do not affect surrounding layout: the original space is still reserved.
Transform functions apply right to left in matrix terms, so order matters (translate(100px) rotate(45deg) differs from rotate(45deg) translate(100px)).
`transform-origin` sets the pivot (default centre).
3D needs perspective on the parent (or in the transform) and transform-style: preserve-3d for nested children, plus `backface-visibility: hidden` for card flips.
Transforms are GPU-accelerated and create a new stacking context and a containing block for fixed descendants.
Percentages in translate refer to the element own size, giving the classic centring trick top:50%; left:50%; translate(-50%, -50%).
Key points
Read more
Example
CodeCentring, hover zoom and 3D card flip:
.modal { position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); }
.zoom:hover { transform: scale(1.05) rotate(2deg); }
.menu-icon { transform-origin: left center; transition: transform .3s; }
.menu-icon.open { transform: rotate(90deg); }
.flip { perspective: 800px; width: 200px; height: 280px; }
.flip-inner { position: relative; width: 100%; height: 100%; transform-style: preserve-3d; transition: transform .6s; }
.flip:hover .flip-inner { transform: rotateY(180deg); }
.face { position: absolute; inset: 0; backface-visibility: hidden; }
.back { transform: rotateY(180deg); }Solved examples
A div has width:200px; padding:20px; border:5px solid; margin:10px; (content-box). Find the total horizontal space it occupies.
Total width
Formula Applied:—Approach note: Distinguish rendered width (without margin) from occupied space (with margin).
Which colour is applied? #box .item { color: red; } .container .item { color: blue; } div.item { color: green; } on <div class="container" id="box"><div class="item">Hi</div></div>.
Winning rule
Formula Applied:—Approach note: Compare tuples left to right; the first larger number wins regardless of later values.
Create a responsive card grid with no media queries.
CSS
Formula Applied:—Approach note: minmax sets minimum card width; 1fr lets cards grow to fill rows.
A modal with z-index: 9999 still appears behind the sticky header with z-index: 2. Why, and how do you fix it?
Cause and fix
Formula Applied:—Approach note: Look for transform, opacity, filter or z-index on ancestors.
Build a holy grail layout with a header, footer, left nav, main and right aside where the footer sticks to the bottom on short pages and the layout stacks on phones.
CSS Grid code
Formula Applied:—Approach note: The 1fr row makes the middle stretch and pushes the footer down.
Real-world applications
Using CSS3 & Modern Styling Architecture in real projects
Every website - navigation bars, card grids, dashboards, themes, micro-interactions and mobile-first designs.
Common mistakes
❌ Myth: Flexbox and Grid are interchangeable.
Why this is wrong: Flexbox is one-dimensional (content-driven); Grid is two-dimensional (layout-driven).
✅ Verified Truth: Use Grid for page/section layouts and Flexbox for aligning items along a line.
⚠️ Exam Tip: State the 1D vs 2D difference.
❌ Myth: !important is a good way to fix specificity issues.
Why this is wrong: It escalates specificity wars and makes CSS hard to maintain.
✅ Verified Truth: Refactor selectors, use cascade layers, or reorder rules.
⚠️ Exam Tip: Mention it only as a last resort.
❌ Myth: width: 100% and padding never overflow.
Why this is wrong: With content-box, padding and border add to the 100% width and cause overflow.
✅ Verified Truth: Use box-sizing: border-box.
⚠️ Exam Tip: Always include the box-sizing reset.
❌ Myth: A larger z-index always puts an element on top.
Why this is wrong: z-index only competes inside the same stacking context.
✅ Verified Truth: Find the ancestors that create contexts, or portal the element to body.
⚠️ Exam Tip: Mention transform, opacity and position as context creators.
❌ Myth: display:none, visibility:hidden and opacity:0 are the same.
Why this is wrong: They differ in layout space, accessibility tree and interactivity.
✅ Verified Truth: none removes entirely; hidden keeps space but is inert; opacity:0 keeps space and stays interactive.
⚠️ Exam Tip: Give a three-way comparison.
❌ Myth: Animating width or top is fine for smooth motion.
Why this is wrong: They trigger layout and paint every frame and can cause jank.
✅ Verified Truth: Animate transform and opacity where possible.
⚠️ Exam Tip: Name the compositor-friendly properties.
Revision notes
CSS controls presentation. This chapter covers selectors and specificity, the box model, units, positioning and stacking, Flexbox and Grid layouts, responsive media queries, custom properties for theming, and transitions, animations and transforms.
High-Yield Quick Revision Points
- selectors: type < class < id; combinators > + ~ and space
- specificity: inline > id > class > element; tie = later rule
- content+padding+border+margin; border-box reset
- rem for text, % / fr for layout, clamp() for fluid, dvh for mobile height
- none removes, hidden keeps space, opacity:0 stays interactive
- static/relative/absolute/fixed/sticky; absolute needs positioned parent
- z-index only within the same stacking context
- Flex = 1D, justify = main axis, align-items = cross axis
- flex: 1 = 1 1 0%; min-width:0 fixes overflow
- Grid = 2D; auto-fit + minmax = responsive grid
- grid-template-areas builds holy grail
- mobile-first min-width media queries
- custom properties on :root; theme via [data-theme]
- transition = state change; @keyframes = autonomous animation; transform = no layout shift
Practice questions
Which property aligns flex items along the main axis?
Specificity of #nav .link a is:
Which declaration makes width include padding and border?
Mobile-first CSS typically uses which kind of media query?
An absolutely positioned child is placed relative to:
Which unit scales with the root font size?
What does flex: 1 expand to?
Which CSS declares a custom property usable as var(--brand)?
Which property is cheapest to animate?
Which keeps the element invisible but still occupying space?