Web Development chapters (5)
  1. 01HTML5 & Semantic Web Architecture
  2. 02CSS3 & Modern Styling Architecture
  3. 03Modern JavaScript (ES6+ & Asynchronous Engine)
  4. 04React.js Frontend Framework
  5. 05Backend Architecture with Node.js & Express

Chapter 02 · HTML, CSS, JS, React, Node

CSS3 & Modern Styling Architecture

16 topics · 3 sections · beginner-friendly study notes · Updated

Share with friends:WhatsAppTelegram

Embed on your site

Free for teachers, schools and blogs. Please keep the attribution link.

Preview

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.

1

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

Code
Selector 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"; }
2

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.

Example

Code
Specificity 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; } }
3

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.

Example

Code
Box 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. */
4

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

Code
Choosing 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 */
5

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.

Example

Code
Display 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;
}
6

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.

Margin (Outer Transparent Space) Border (Stroke Boundary) Padding (Inner Breathing Space) Content (width × height)
CSS3 & Modern Styling Architecture

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

  • Containing block: Box against which offsets and percentages of a positioned element are resolved.
  • Out of flow: Absolute/fixed elements no longer take space in the normal layout.
  • inset: Shorthand for top, right, bottom and left.

Example

Code
Common 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 */
7

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

  • Stacking context: Group whose children are stacked independently of the outside.
  • isolation: isolate: Creates a new stacking context without side effects.
  • z-index: auto: Default: no new context, painted in tree order.

Example

Code
Stacking 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 */
8

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.

Example

Code
Flexbox 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 */
9

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".

Flex Container (display: flex; justify-content: space-between; align-items: center;) Main Axis (Row) ➜ Cross Axis ⬇ Flex Item 1 flex: 1 Flex Item 2 flex: 2 (Grows) Flex Item 3 flex: 1
CSS3 & Modern Styling Architecture

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.

Example

Code
Grow, 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; }
10

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

Code
Grid 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; }
11

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

  • grid-template-areas: Named layout map of the grid.
  • grid-area: Assigns an element to a named area (or sets row/column lines).
  • Holy Grail layout: Header, footer, centre content and two sidebars with equal-height columns.

Example

Code
Holy 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";
  }
}
12

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.

Example

Code
Mobile-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; } }
13

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.

Variable → value in memory

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

  • Custom property: User-defined property starting with -- that holds reusable values.
  • var(): Function that reads a custom property with an optional fallback.
  • Design token: Named design value (colour, spacing) shared across a UI.

Example

Code
Theme 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"); */
14

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

  • Timing function: Curve describing the speed of the transition.
  • Compositor properties: transform and opacity - animated without layout or paint.
  • transitionend: Event fired when a transition completes.

Example

Code
Hover 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; }
15

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

Code
Spinner, 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; } }
16

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.

Page structure + style

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

  • transform-origin: Point around which rotation or scaling happens.
  • perspective: Depth distance giving 3D transforms their vanishing point.
  • preserve-3d: Keeps child elements in the 3D space of the parent.

Read more

Example

Code
Centring, 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

Example 01 · Basic

A div has width:200px; padding:20px; border:5px solid; margin:10px; (content-box). Find the total horizontal space it occupies.

Given Data:
    Required To Find:

    Total width

    Formula Applied:—
    Step-by-Step Solution:
    Step 1: Content = 200
    Step 2: Padding both sides = 40
    Step 3: Border both sides = 10
    Step 4: Margin both sides = 20
    Step 5: Total = 200+40+10+20
    Final Answer: 270px total space (rendered box width = 250px). With border-box the rendered width would be 200px.

    Approach note: Distinguish rendered width (without margin) from occupied space (with margin).

    Example 02 · Intermediate

    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>.

    Given Data:
      Required To Find:

      Winning rule

      Formula Applied:—
      Step-by-Step Solution:
      Step 1: #box .item = (0,1,1,0)
      Step 2: .container .item = (0,0,2,0)
      Step 3: div.item = (0,0,1,1)
      Step 4: Highest is the id selector
      Final Answer: red

      Approach note: Compare tuples left to right; the first larger number wins regardless of later values.

      Example 03 · Intermediate

      Create a responsive card grid with no media queries.

      Given Data:
        Required To Find:

        CSS

        Formula Applied:—
        Step-by-Step Solution:
        Step 1: display:grid on the container
        Step 2: Use repeat(auto-fit, minmax(220px,1fr))
        Step 3: Add gap
        Final Answer: .cards { display:grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap:20px; }

        Approach note: minmax sets minimum card width; 1fr lets cards grow to fill rows.

        Example 04 · Intermediate

        A modal with z-index: 9999 still appears behind the sticky header with z-index: 2. Why, and how do you fix it?

        Given Data:
          Required To Find:

          Cause and fix

          Formula Applied:—
          Step-by-Step Solution:
          Step 1: The modal lives inside a parent that creates its own stacking context (e.g. position:relative; z-index:1 or a transform)
          Step 2: z-index is compared only within that context, so 9999 cannot escape it
          Step 3: Move the modal to the end of body (portal) or remove the context-creating property from the ancestor
          Step 4: Alternatively raise the ancestor z-index above the header
          Final Answer: The modal is trapped in a lower stacking context; render it as a direct child of body or adjust the ancestor so it is no longer a lower context.

          Approach note: Look for transform, opacity, filter or z-index on ancestors.

          Example 05 · Advanced

          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.

          Given Data:
            Required To Find:

            CSS Grid code

            Formula Applied:—
            Step-by-Step Solution:
            Step 1: Container: display:grid; min-height:100vh
            Step 2: Columns 200px 1fr 200px, rows auto 1fr auto
            Step 3: Define grid-template-areas and assign grid-area
            Step 4: In a media query switch to one column and stack the areas
            Final Answer: .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"; } @media (max-width:700px){ .page{ grid-template-columns:1fr; grid-template-areas:"header" "nav" "main" "aside" "footer"; } }

            Approach note: The 1fr row makes the middle stretch and pushes the footer down.

            Real-world applications

            Web

            Using CSS3 & Modern Styling Architecture in real projects

            Every website - navigation bars, card grids, dashboards, themes, micro-interactions and mobile-first designs.

            Mechanism: Write small programs, read errors carefully, then grow complexity only after the basics are solid.

            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

            1. selectors: type < class < id; combinators > + ~ and space
            2. specificity: inline > id > class > element; tie = later rule
            3. content+padding+border+margin; border-box reset
            4. rem for text, % / fr for layout, clamp() for fluid, dvh for mobile height
            5. none removes, hidden keeps space, opacity:0 stays interactive
            6. static/relative/absolute/fixed/sticky; absolute needs positioned parent
            7. z-index only within the same stacking context
            8. Flex = 1D, justify = main axis, align-items = cross axis
            9. flex: 1 = 1 1 0%; min-width:0 fixes overflow
            10. Grid = 2D; auto-fit + minmax = responsive grid
            11. grid-template-areas builds holy grail
            12. mobile-first min-width media queries
            13. custom properties on :root; theme via [data-theme]
            14. transition = state change; @keyframes = autonomous animation; transform = no layout shift

            Practice questions

            Question 1 · MCQ (Interview / semester)

            Which property aligns flex items along the main axis?

            Question 2 · MCQ (Interview / semester)

            Specificity of #nav .link a is:

            Question 3 · MCQ (Interview / semester)

            Which declaration makes width include padding and border?

            Question 4 · MCQ (Interview / semester)

            Mobile-first CSS typically uses which kind of media query?

            Question 5 · MCQ (Interview / semester)

            An absolutely positioned child is placed relative to:

            Question 6 · MCQ (Interview / semester)

            Which unit scales with the root font size?

            Question 7 · MCQ (Interview / semester)

            What does flex: 1 expand to?

            Question 8 · MCQ (Interview / semester)

            Which CSS declares a custom property usable as var(--brand)?

            Question 9 · MCQ (Interview / semester)

            Which property is cheapest to animate?

            Question 10 · MCQ (Interview / semester)

            Which keeps the element invisible but still occupying space?