Internet Programming Laboratory

Unit 3: CSS3 & Modern Layouts

Selectors, Specificity, Box Model, Flexbox, Grid, CSS Variables, Typography, Responsive Design, Transitions & Animations โ€” the visual layer that turns HTML skeletons into stunning, production-ready interfaces.

๐Ÿข Industry-Aligned  |  ๐Ÿ“ 15 MCQs (Bloom's Taxonomy)  |  ๐Ÿ”ฌ 5 Lab Exercises  |  ๐Ÿ’ผ Interview Prep

Section 1

Why This Chapter Matters in 2025

HTML gives you the skeleton. CSS gives you the skin, clothes, and personality. Without CSS, every website on earth would look like a plain text document from 1995. The difference between a โ‚น500/month freelancer and a โ‚น15 LPA frontend engineer? Mastery of CSS layout, responsiveness, and modern design patterns.

Here's a reality check: Flexbox and CSS Grid are now used in 97% of production websites worldwide. If you still use float: left to build layouts in 2025, your code will be rejected in every company code review.

๐Ÿข Industry Connection โ€” Who Relies on CSS3 in Production?

CRED โ€” their dark-themed, glassmorphic UI? Every gradient, every smooth card hover, every subtle animation is pure CSS3. Their design team writes CSS Variables for the entire theme system โ€” change one variable, the whole app changes.

Swiggy โ€” their restaurant grid? CSS Grid. Their mobile menu? Flexbox. Their "Add to Cart" animation? CSS @keyframes. Swiggy's frontend team rejected float-based layouts in 2018.

Zerodha (Kite) โ€” India's largest stock trading platform. Their real-time trading dashboard uses CSS Grid for the multi-panel layout, CSS Variables for light/dark theme switching, and media queries for tablet-to-desktop responsiveness. Zero JavaScript for layout.

๐Ÿ‡ฎ๐Ÿ‡ณ CRED๐Ÿ‡ฎ๐Ÿ‡ณ Swiggy๐Ÿ‡ฎ๐Ÿ‡ณ Zerodha๐Ÿ‡ฎ๐Ÿ‡ณ Flipkart๐Ÿ‡ฎ๐Ÿ‡ณ Razorpay

Prerequisite Checklist โœ…

  • โœ… Completed Unit 1 & 2 (HTML5 fundamentals โ€” you need elements to style)
  • โœ… VS Code with the Live Server extension installed (instant preview on save)
  • โœ… Chrome DevTools โ€” you'll live in the "Elements โ†’ Styles" panel this entire unit
  • โœ… Basic understanding of HTML tags, classes, and IDs
The first CSS specification was proposed by Hรฅkon Wium Lie in 1994. Before CSS, developers used HTML <font> tags and <table> layouts. A single colour change required editing every page manually. CSS changed everything โ€” one stylesheet, one change, every page updated.
Section 2

Learning Outcomes โ€” Bloom's Taxonomy

Bloom's LevelLearning Outcome
L1 โ€” RememberRecall the syntax for CSS rules, selectors (type, class, id, attribute, pseudo-class, pseudo-element), and the box model components
L2 โ€” UnderstandExplain how CSS specificity and the cascade determine which styles are applied when rules conflict
L3 โ€” ApplyBuild responsive layouts using Flexbox and CSS Grid, apply Google Fonts, and implement CSS Variables for a design system
L4 โ€” AnalyzeDebug layout issues using Chrome DevTools โ€” inspect computed box model, identify specificity conflicts, and diagnose overflow problems
L5 โ€” EvaluateCompare Flexbox vs Grid for a given layout requirement and justify which approach is more maintainable and performant
L6 โ€” CreateDesign and implement a complete, responsive, themed landing page for an Indian startup using CSS3, Flexbox, Grid, variables, and animations
Section 3

Concept Explanations โ€” Theory, Earned

3.1 CSS Rules & Linking Methods

What it is

A CSS rule is the fundamental unit of styling. It has two parts: a selector (what to style) and a declaration block (how to style it). Every visual change you see on any website is the result of CSS rules.

Anatomy of a CSS Rule
CSS
/* SELECTOR โ†’ DECLARATION BLOCK */
h1 {
  color: #0f172a;           /* Property: value; */
  font-size: 2rem;         /* Each line is a "declaration" */
  font-weight: 900;
  margin-bottom: 16px;
}
/* โ†‘ Selector   โ†‘ Declaration Block (curly braces) */
Three Ways to Add CSS
External CSS โ€” The industry standard. You write CSS in a separate .css file and link it with <link>. Every company โ€” Flipkart, CRED, Google โ€” uses external stylesheets. This is non-negotiable.
MethodSyntaxUse CaseIndustry?
External (link)<link rel="stylesheet" href="style.css">All production code โ€” separation of concernsโœ… Yes
Internal (style)<style> ... </style> in <head>Single-page demos, email templatesโš ๏ธ Rare
Inlinestyle="color:red" on elementQuick overrides, dynamic JS stylesโš ๏ธ Avoid
@import@import url('other.css'); inside CSSModular CSS files (design systems)โœ… Yes
HTML
<!-- ๐Ÿ“ index.html -->
<!-- METHOD 1: External CSS (INDUSTRY STANDARD) -->
<head>
  <link rel="stylesheet" href="styles/main.css">
  <link rel="stylesheet" href="styles/responsive.css">
</head>

<!-- METHOD 2: Internal CSS (for demos only) -->
<head>
  <style>
    body { font-family: 'Inter', sans-serif; }
  </style>
</head>

<!-- METHOD 3: Inline CSS (avoid in production) -->
<p style="color: red; font-weight: bold;">Urgent notice</p>
Float-based layouts (float: left; clear: both;) โ€” replaced by Flexbox and Grid since 2017. Floats are for wrapping text around images, not building page layouts. If you see a tutorial using floats for column layouts, close the tab.

3.2 Selectors & Specificity โ€” The Heart of CSS

Why it matters

Selectors are how you target elements. The difference between a junior and a senior CSS developer? The senior writes precise selectors that don't accidentally break other elements. Specificity is the algorithm browsers use to resolve conflicts.

Selector Types โ€” Complete Reference
SelectorExampleWhat it SelectsSpecificity
TypepAll <p> elements0-0-1
Class.cardAll elements with class="card"0-1-0
ID#heroThe element with id="hero"1-0-0
Attribute[type="email"]All inputs with type="email"0-1-0
Pseudo-classa:hoverLinks on mouse hover0-1-0
Pseudo-classli:nth-child(odd)Odd-numbered list items0-1-0
Pseudo-classinput:focusCurrently focused input0-1-0
Pseudo-elementp::first-lineFirst line of every paragraph0-0-1
Pseudo-element.card::beforeGenerated content before .card0-1-1
Descendantnav aAll <a> inside <nav>0-0-2
Childul > liDirect <li> children of <ul>0-0-2
Universal*Everything0-0-0
CSS
/* ๐Ÿข SWIGGY-STYLE: Selector Examples */

/* Type selector - all paragraphs */
p { line-height: 1.6; }

/* Class selector - reusable card component */
.restaurant-card {
  border-radius: 16px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.08);
}

/* ID selector - unique hero section */
#hero-banner { min-height: 70vh; }

/* Attribute selector - style email inputs differently */
input[type="email"] { border-color: #6366f1; }

/* Pseudo-class :hover - button hover effect */
.btn-order:hover {
  background: #ea580c;
  transform: translateY(-2px);
}

/* Pseudo-class :nth-child - zebra striping */
.menu-item:nth-child(even) { background: #f8fafc; }

/* Pseudo-element ::before - decorative icon */
.rating::before {
  content: 'โญ';
  margin-right: 4px;
}

/* Combining selectors - nav links that are hovered */
nav.main-nav a:hover {
  color: #ea580c;
  border-bottom: 2px solid currentColor;
}
Specificity โ€” The Cascade Algorithm

When two rules target the same element, the browser uses specificity to decide which wins. Think of it as a scoring system: (ID, CLASS, TYPE).

CSS
/* SPECIFICITY BATTLE โ€” Who wins? */

p             { color: black; }   /* Specificity: 0-0-1 */
.intro        { color: blue;  }   /* Specificity: 0-1-0  โ† WINS over p */
#welcome      { color: green; }   /* Specificity: 1-0-0  โ† WINS over .intro */
p.intro       { color: red;   }   /* Specificity: 0-1-1  โ† still loses to #welcome */

/* ๐Ÿšจ NEVER DO THIS โ€” !important breaks the cascade */
p { color: purple !important; }  /* Nuclear option โ€” overrides everything */

Using !important to fix styling issues. If you find yourself writing !important, you have a specificity problem โ€” fix the selector, don't use the nuclear option. At CRED and Razorpay, !important in production CSS triggers an automatic code review flag.

3.3 The CSS Box Model โ€” Every Element is a Box

What it is

Every single HTML element โ€” from a <div> to a <span> โ€” is rendered as a rectangular box. The box model defines four layers: content โ†’ padding โ†’ border โ†’ margin.

ASCII
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚                   MARGIN                      โ”‚  โ† Space OUTSIDE the border
โ”‚  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”     โ”‚
โ”‚  โ”‚              BORDER                  โ”‚     โ”‚  โ† The visible edge
โ”‚  โ”‚  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”    โ”‚     โ”‚
โ”‚  โ”‚  โ”‚          PADDING             โ”‚    โ”‚     โ”‚  โ† Space INSIDE the border
โ”‚  โ”‚  โ”‚  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”    โ”‚    โ”‚     โ”‚
โ”‚  โ”‚  โ”‚  โ”‚                      โ”‚    โ”‚    โ”‚     โ”‚
โ”‚  โ”‚  โ”‚  โ”‚      CONTENT         โ”‚    โ”‚    โ”‚     โ”‚  โ† Your text, images, etc.
โ”‚  โ”‚  โ”‚  โ”‚   (width ร— height)   โ”‚    โ”‚    โ”‚     โ”‚
โ”‚  โ”‚  โ”‚  โ”‚                      โ”‚    โ”‚    โ”‚     โ”‚
โ”‚  โ”‚  โ”‚  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜    โ”‚    โ”‚     โ”‚
โ”‚  โ”‚  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜    โ”‚     โ”‚
โ”‚  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜     โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
The box-sizing Problem
โŒ Default: content-box
/* width: 300px but ACTUAL width = 300 + 20 + 20 + 2 + 2 = 344px! */
.card {
  width: 300px;
  padding: 20px;
  border: 2px solid #ccc;
  /* Total width: 344px โ€” SURPRISE! ๐Ÿ˜ฑ */
}
โœ… Modern: border-box
/* width: 300px and ACTUAL width = 300px. Period. */
* { box-sizing: border-box; }
.card {
  width: 300px;
  padding: 20px;
  border: 2px solid #ccc;
  /* Total width: 300px โ€” as expected โœ… */
}
Every production CSS file starts with this reset. Flipkart, Swiggy, CRED โ€” everyone uses * { box-sizing: border-box; } as the very first rule. It makes width calculations predictable.
CSS
/* ๐Ÿข INDUSTRY STANDARD RESET โ€” Start every project with this */
*,
*::before,
*::after {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

html {
  scroll-behavior: smooth;     /* Smooth anchor scrolling */
}

body {
  font-family: 'Inter', system-ui, sans-serif;
  line-height: 1.6;
  color: #1e293b;
  background: #f8fafc;
}

3.4 Flexbox Layout โ€” One-Dimensional Powerhouse

What it is

Flexbox is a one-dimensional layout system โ€” it handles either a row or a column at a time. It replaced float-based layouts and is the go-to for navbars, card rows, centering elements, and any single-axis alignment.

Flexbox โ€” short for "Flexible Box Layout Module." Introduced in CSS3 and supported by 99.5% of browsers globally. If you've used Swiggy's app, every restaurant card row, every filter bar, and every checkout step is Flexbox.
Core Concepts
ASCII
FLEX CONTAINER (display: flex)
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚                                                      โ”‚
โ”‚   โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”   โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”   โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”          โ”‚
โ”‚   โ”‚ FLEX    โ”‚   โ”‚ FLEX    โ”‚   โ”‚ FLEX    โ”‚          โ”‚  โ† main-axis โ†’
โ”‚   โ”‚ ITEM 1  โ”‚   โ”‚ ITEM 2  โ”‚   โ”‚ ITEM 3  โ”‚          โ”‚
โ”‚   โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜   โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜   โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜          โ”‚
โ”‚                                                      โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                                                        โ†• cross-axis

Parent properties: display, flex-direction, justify-content, align-items, flex-wrap, gap
Child properties:  flex-grow, flex-shrink, flex-basis, align-self, order
CSS
/* ๐Ÿข SWIGGY-STYLE: Restaurant Card Row */
.restaurant-grid {
  display: flex;              /* Activate Flexbox */
  flex-wrap: wrap;            /* Cards wrap to next line */
  gap: 20px;                  /* Space between cards (modern โ€” no margin hacks) */
  justify-content: center;   /* Center cards horizontally */
}

.restaurant-card {
  flex: 0 1 300px;            /* Don't grow, can shrink, base width 300px */
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0,0,0,0.08);
}

/* ๐Ÿข FLIPKART-STYLE: Navbar */
.navbar {
  display: flex;
  justify-content: space-between;  /* Logo left, links right */
  align-items: center;            /* Vertically centered */
  padding: 0 24px;
  height: 64px;
  background: #2874f0;            /* Flipkart blue */
}

/* ๐ŸŽฏ CENTERING โ€” The classic interview question */
.center-everything {
  display: flex;
  justify-content: center;  /* Horizontal center */
  align-items: center;      /* Vertical center */
  min-height: 100vh;        /* Full viewport height */
}
Flexbox Properties โ€” Quick Reference
PropertyValuesEffect
flex-directionrow | column | row-reverse | column-reverseSets the main axis direction
justify-contentflex-start | center | space-between | space-around | space-evenlyAlignment along main axis
align-itemsstretch | center | flex-start | flex-end | baselineAlignment along cross axis
flex-wrapnowrap | wrap | wrap-reverseWhether items wrap to next line
gap16px | 1rem 2remSpace between items (row-gap column-gap)
flexgrow shrink basisShorthand: flex: 1 0 auto
align-selfSame as align-itemsOverride alignment for one item

3.5 CSS Grid Layout โ€” Two-Dimensional Layouts

What it is

CSS Grid is a two-dimensional layout system โ€” it handles rows and columns simultaneously. Use it for full page layouts, dashboards, image galleries, and any layout where you need to control both axes.

CSS Grid โ€” the most powerful layout system in CSS. Zerodha Kite's trading dashboard, Flipkart's product grid, and CRED's card layout all use CSS Grid. It's not a replacement for Flexbox โ€” they're complementary.
CSS
/* ๐Ÿข ZERODHA KITE-STYLE: Trading Dashboard Layout */
.dashboard {
  display: grid;
  grid-template-columns: 250px 1fr 300px;  /* Sidebar | Main | Watchlist */
  grid-template-rows: 64px 1fr 40px;       /* Header | Content | Footer */
  grid-template-areas:
    "header  header   header"
    "sidebar main     watch"
    "footer  footer   footer";
  height: 100vh;
  gap: 0;
}

.header  { grid-area: header;  }
.sidebar { grid-area: sidebar; }
.main    { grid-area: main;    }
.watch   { grid-area: watch;   }
.footer  { grid-area: footer;  }

/* ๐Ÿข FLIPKART-STYLE: Product Grid */
.product-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  gap: 20px;
  padding: 20px;
}
/* โ†‘ auto-fill + minmax = responsive grid WITHOUT media queries! */
/* Cards are minimum 240px, grow to fill space, wrap automatically */
Grid Properties โ€” Quick Reference
PropertyExampleEffect
grid-template-columns200px 1fr 1fr3 columns: fixed + 2 flexible
grid-template-rowsauto 1fr autoHeader, stretchy body, footer
grid-template-areas"header header" "side main"Named areas for placement
repeat()repeat(3, 1fr)Three equal columns
minmax()minmax(200px, 1fr)Minimum 200px, stretch to fill
auto-fillrepeat(auto-fill, minmax(250px, 1fr))Auto-responsive grid
gap16px 24pxRow gap & column gap
grid-columnspan 2Item spans 2 columns
Flexbox vs Grid โ€” When to Use Which?
ScenarioUseWhy
Navbar with logo + linksFlexboxSingle row, space-between
Product card gridGrid2D layout, auto-fill responsive
Centering a modalFlexboxSimple 1D centering
Full page dashboardGridNamed areas, rows + columns
Card content (icon + text)FlexboxSingle row alignment
Image gallery with spanningGridItems can span multiple cells

3.6 CSS Variables (Custom Properties) โ€” Design Systems

What it is

CSS Variables (officially called Custom Properties) let you define reusable values. Change one variable, and every element using it updates instantly. This is how companies like CRED implement dark mode โ€” one variable swap.

CSS
/* ๐Ÿข CRED-STYLE: Design System with CSS Variables */
:root {
  /* Colour palette */
  --primary: #1e1e2e;
  --primary-light: #2a2a3e;
  --accent: #c084fc;
  --text: #e2e8f0;
  --text-muted: #94a3b8;
  --surface: #1e293b;

  /* Typography */
  --font-body: 'Inter', sans-serif;
  --font-code: 'Fira Code', monospace;

  /* Spacing scale (8px base) */
  --space-xs: 4px;
  --space-sm: 8px;
  --space-md: 16px;
  --space-lg: 24px;
  --space-xl: 48px;

  /* Border radius */
  --radius-sm: 8px;
  --radius-md: 12px;
  --radius-lg: 20px;
  --radius-full: 9999px;
}

/* Using variables */
.card {
  background: var(--surface);
  color: var(--text);
  padding: var(--space-lg);
  border-radius: var(--radius-md);
  font-family: var(--font-body);
}

/* ๐ŸŒ™ Dark/Light theme switch โ€” just change the variables! */
[data-theme="light"] {
  --primary: #ffffff;
  --text: #1e293b;
  --surface: #f8fafc;
  --accent: #7c3aed;
}
CSS Variables cascade. You can redefine a variable inside a specific component, and only that component changes. This is why large teams love them โ€” global defaults + local overrides.

3.7 Fonts & Typography โ€” Google Fonts & Modern Scale

What it is

Typography is 90% of web design. The right font, size, weight, and spacing make the difference between "amateur student project" and "professional product." In 2025, every company uses Google Fonts or custom web fonts.

HTML
<!-- ๐Ÿ“ Load Google Fonts in <head> -->
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800;900&display=swap"
      rel="stylesheet">
CSS
/* ๐Ÿข RAZORPAY-STYLE: Typography System */
body {
  font-family: 'Inter', system-ui, -apple-system, sans-serif;
  font-size: 1rem;          /* 16px โ€” browser default, accessible */
  line-height: 1.6;        /* 160% โ€” comfortable reading */
  color: #1e293b;
  -webkit-font-smoothing: antialiased;
}

h1 { font-size: 2.5rem; font-weight: 900; letter-spacing: -0.02em; line-height: 1.1; }
h2 { font-size: 1.8rem; font-weight: 800; letter-spacing: -0.01em; }
h3 { font-size: 1.3rem; font-weight: 700; }
h4 { font-size: 1.1rem; font-weight: 600; }

/* Responsive font sizes using clamp() โ€” modern approach */
.hero-title {
  font-size: clamp(2rem, 5vw, 4rem);
  /* Minimum 2rem, scales with viewport, maximum 4rem */
}
Font Size Units โ€” When to Use What
UnitBaseUse CaseExample
remRoot font-size (16px)Body text, headings โ€” scales globally1.5rem = 24px
emParent's font-sizePadding relative to font sizepadding: 0.5em
pxAbsolute pixelBorders, shadows, precise controlborder: 1px solid
vw/vhViewport width/heightHero sections, full-screen layoutsmin-height: 100vh
%Parent elementWidths, max-widthwidth: 100%

3.8 Responsive Design โ€” Mobile-First & Media Queries

What it is

Responsive design means your website adapts to any screen โ€” mobile, tablet, desktop, ultrawide. In India, 70%+ of web traffic comes from mobile phones. If your site isn't mobile-first, you've already lost 70% of your users.

Mobile-First โ€” Write CSS for mobile screens first, then add complexity for larger screens using min-width media queries. This is the industry standard at Flipkart, Swiggy, Meesho, and every Indian tech company.
CSS
/* ๐Ÿข MOBILE-FIRST APPROACH โ€” Start with mobile, scale up */

/* BASE STYLES โ€” Mobile phones (0 - 768px) */
.product-grid {
  display: grid;
  grid-template-columns: 1fr;          /* Single column on mobile */
  gap: 16px;
  padding: 12px;
}

.navbar {
  flex-direction: column;              /* Stack vertically on mobile */
  padding: 12px;
}

/* TABLET โ€” 768px and above */
@media (min-width: 768px) {
  .product-grid {
    grid-template-columns: repeat(2, 1fr); /* 2 columns */
    gap: 20px;
    padding: 20px;
  }
  .navbar {
    flex-direction: row;                  /* Horizontal on tablet+ */
    justify-content: space-between;
  }
}

/* DESKTOP โ€” 1024px and above */
@media (min-width: 1024px) {
  .product-grid {
    grid-template-columns: repeat(3, 1fr); /* 3 columns */
    gap: 24px;
    padding: 32px;
  }
}

/* LARGE DESKTOP โ€” 1440px and above */
@media (min-width: 1440px) {
  .product-grid {
    grid-template-columns: repeat(4, 1fr); /* 4 columns */
    max-width: 1400px;
    margin: 0 auto;
  }
}
Common Breakpoints
DeviceBreakpointCommon Use
Mobile (portrait)0 โ€“ 480pxSingle column, stacked layout
Mobile (landscape) / Small tablet481px โ€“ 768px2-column grid, horizontal nav
Tablet / Small laptop769px โ€“ 1024px3-column grid, sidebar visible
Desktop1025px โ€“ 1440pxFull layout, max-width container
Large desktop / Ultrawide1441px+Wider content, more columns

3.9 Background Images & Gradients

CSS
/* ๐Ÿข CRED-STYLE: Gradient backgrounds */

/* Linear gradient */
.hero {
  background: linear-gradient(135deg, #1e1b4b, #312e81, #4338ca);
  color: #fff;
  min-height: 60vh;
}

/* Radial gradient */
.spotlight {
  background: radial-gradient(circle at 30% 50%, #4338ca 0%, #0f172a 70%);
}

/* Background image with overlay */
.banner {
  background: linear-gradient(rgba(0,0,0,0.6), rgba(0,0,0,0.6)),
              url('banner.jpg') center/cover no-repeat;
  /* โ†‘ overlay gradient  โ†‘ image shorthand */
}

/* Glassmorphism effect (CRED-style) */
.glass-card {
  background: rgba(255, 255, 255, 0.05);
  backdrop-filter: blur(16px);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 20px;
}

3.10 Styling Tables & Forms

CSS
/* ๐Ÿข IRCTC-STYLE: Styled Data Table */
.train-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 0.9rem;
  overflow: hidden;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.08);
}

.train-table th {
  background: #1e40af;
  color: #fff;
  padding: 14px 16px;
  text-align: left;
  font-weight: 700;
}

.train-table td {
  padding: 12px 16px;
  border-bottom: 1px solid #e2e8f0;
}

.train-table tr:nth-child(even) {
  background: #f8fafc;
}

.train-table tr:hover {
  background: #eff6ff;
}

/* ๐Ÿข OYO-STYLE: Styled Form Inputs */
.form-input {
  width: 100%;
  padding: 14px 16px;
  font-size: 1rem;
  border: 2px solid #e2e8f0;
  border-radius: 12px;
  outline: none;
  transition: border-color 0.2s, box-shadow 0.2s;
  font-family: inherit;
}

.form-input:focus {
  border-color: #6366f1;
  box-shadow: 0 0 0 4px rgba(99, 102, 241, 0.1);
}

.form-input::placeholder {
  color: #94a3b8;
}

3.11 CSS Transitions & Animations

Transitions โ€” Smooth State Changes

Transitions animate changes between two states. When you hover a button and it smoothly changes colour โ€” that's a transition.

CSS
/* ๐Ÿข SWIGGY-STYLE: Button with hover transition */
.btn-order {
  background: #ea580c;
  color: #fff;
  padding: 14px 32px;
  border: none;
  border-radius: 12px;
  font-size: 1rem;
  font-weight: 700;
  cursor: pointer;
  transition: all 0.2s ease;  /* โ† The magic line */
}

.btn-order:hover {
  background: #c2410c;
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(234, 88, 12, 0.3);
}

.btn-order:active {
  transform: translateY(0);
  box-shadow: 0 2px 6px rgba(234, 88, 12, 0.2);
}

/* Card lift on hover */
.product-card {
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}
.product-card:hover {
  transform: translateY(-6px);
  box-shadow: 0 12px 32px rgba(0,0,0,0.12);
}
@keyframes Animations โ€” Complex Multi-Step Animations
CSS
/* ๐Ÿข Loading spinner (Flipkart checkout) */
@keyframes spin {
  0%   { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #e2e8f0;
  border-top-color: #6366f1;
  border-radius: 50%;
  animation: spin 0.8s linear infinite;
}

/* ๐Ÿข Fade-in on scroll (CRED-style) */
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.animate-in {
  animation: fadeInUp 0.6s ease forwards;
}

/* Pulse effect for notifications */
@keyframes pulse {
  0%, 100% { transform: scale(1); }
  50%      { transform: scale(1.05); }
}

.notification-badge {
  animation: pulse 2s ease-in-out infinite;
}
Respect user preferences for reduced motion. Some users experience motion sickness from animations. Always include this media query:
@media (prefers-reduced-motion: reduce) {
  * {
    animation-duration: 0.01ms !important;
    transition-duration: 0.01ms !important;
  }
}
Section 4

Industry Problems โ€” CSS in the Real World

๐Ÿข Case Study 1: Swiggy's Responsive Restaurant Grid

The Problem: Swiggy serves 50M+ users. Their restaurant listing page must work on โ‚น8,000 phones (320px screens) and โ‚น2L ultrawide monitors (2560px). The grid must auto-adjust: 1 column on mobile, 2 on tablet, 3 on desktop, 4 on ultrawide โ€” without JavaScript.

The CSS Solution:

CSS
.restaurant-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
  padding: 16px;
}

/* That's it. ONE LINE handles all breakpoints. */
/* auto-fill = create as many columns as fit */
/* minmax(280px, 1fr) = minimum 280px, stretch to fill */

Why This Matters: This single CSS declaration replaces what would have been 4 separate media queries. It's self-adapting โ€” add a 5th column on ultrawide? Automatic. Shrink to 1 column on mobile? Automatic.

๐Ÿข Case Study 2: CRED's Dark Mode Theme System

The Problem: CRED needs to support both dark and light themes across 100+ components. Changing colours in every component individually would require editing 500+ files.

The CSS Solution:

CSS
/* Define all colours as CSS Variables */
:root {
  --bg: #0a0a0f;
  --card-bg: #1a1a2e;
  --text: #e8e8e8;
  --accent: #c084fc;
  --border: rgba(255,255,255,0.08);
}

[data-theme="light"] {
  --bg: #f9fafb;
  --card-bg: #ffffff;
  --text: #1e293b;
  --accent: #7c3aed;
  --border: rgba(0,0,0,0.08);
}

/* Every component uses variables โ€” zero hardcoded colours */
.credit-card {
  background: var(--card-bg);
  color: var(--text);
  border: 1px solid var(--border);
}

Result: Theme switch happens by toggling ONE attribute on <html>. Zero JavaScript style changes. Zero component modifications.

๐Ÿข Case Study 3: Zerodha Kite's Trading Dashboard

The Problem: A trading dashboard with a fixed header, collapsible sidebar, main chart area, and watchlist panel. All must resize independently. The layout must not reflow during real-time stock price updates.

The CSS Solution:

CSS
.kite-dashboard {
  display: grid;
  grid-template-columns: var(--sidebar-width, 240px) 1fr 320px;
  grid-template-rows: 56px 1fr 32px;
  grid-template-areas:
    "header  header  header"
    "sidebar chart   watch"
    "footer  footer  footer";
  height: 100vh;
  overflow: hidden;
}

/* Sidebar collapse โ€” just change the variable */
.kite-dashboard.sidebar-collapsed {
  --sidebar-width: 48px;
}

/* Responsive: hide watchlist on mobile */
@media (max-width: 768px) {
  .kite-dashboard {
    grid-template-columns: 1fr;
    grid-template-areas:
      "header"
      "chart"
      "footer";
  }
}
Section 5

Lab Exercises โ€” Hands-On Practice

Lab 1: CSS Selectors & Specificity Playground

โฑ 30 minutesBeginner

Objective: Master CSS selectors by styling a restaurant menu page without modifying the HTML.

Instructions:

  1. Create menu.html with the following structure: a header, nav with 4 links, main section with 6 menu item cards (each with name, price, and a "vegetarian" or "non-veg" class), and a footer.
  2. Create menu.css and style it using only these selector types:
    • Type selectors for base typography
    • Class selectors for card styling
    • Pseudo-class :hover for card hover effects
    • Pseudo-class :nth-child(even) for alternate row backgrounds
    • Attribute selector [data-spicy="true"] to highlight spicy items in red
    • Pseudo-element ::before to add a โœ… icon before vegetarian items
  3. Demonstrate a specificity conflict: style the same element with a type, class, and ID selector โ€” document which wins and why.

Expected Output: A styled menu page with hover effects, zebra striping, visual vegetarian indicators, and a documented specificity battle.

Lab 2: Flexbox โ€” Build a Flipkart-Style Navbar

โฑ 35 minutesIntermediate

Objective: Build a responsive navigation bar using Flexbox that matches Flipkart's layout.

Requirements:

  1. Create a navbar with: Logo (left), Search bar (center, flexible width), and User icons (right โ€” login, cart, more).
  2. Use display: flex, justify-content: space-between, align-items: center.
  3. The search bar should use flex: 1 to fill available space between logo and icons.
  4. Add hover effects on nav links (underline slides in from left using ::after pseudo-element + transition).
  5. On screens below 768px, hide the search bar and show a search icon instead.
CSS
/* Hint: Sliding underline on hover */
.nav-link {
  position: relative;
}
.nav-link::after {
  content: '';
  position: absolute;
  bottom: -4px;
  left: 0;
  width: 0;
  height: 2px;
  background: #fff;
  transition: width 0.3s ease;
}
.nav-link:hover::after {
  width: 100%;
}

Lab 3: CSS Grid โ€” Build a Zerodha-Style Dashboard

โฑ 45 minutesIntermediate

Objective: Build a multi-panel dashboard layout using CSS Grid with named areas.

Requirements:

  1. Create a full-viewport layout with: Header (64px), Sidebar (250px), Main chart area (flexible), Watchlist panel (300px), Footer (40px).
  2. Use grid-template-areas with named areas: "header", "sidebar", "main", "watchlist", "footer".
  3. Header and footer span all columns.
  4. Add a responsive breakpoint at 768px: collapse to single column, hide sidebar and watchlist.
  5. Style the sidebar with a dark background (#0f172a), the main area with a light background, and the watchlist with a slightly different shade.
  6. Add smooth hover transitions on sidebar nav items.

Expected Output: A full-page dashboard that looks and behaves like a real trading platform.

Lab 4: CSS Variables & Theming โ€” Build a Dark/Light Toggle

โฑ 40 minutesIntermediate

Objective: Implement a complete theme system using CSS Variables with a dark/light mode toggle.

Requirements:

  1. Define a design system in :root with variables for: colors (background, surface, text, primary, accent), spacing (4 sizes), border-radius (3 sizes), and fonts.
  2. Create a [data-theme="dark"] and [data-theme="light"] selector that overrides the colour variables.
  3. Build a simple card-based UI (3 cards, a header, and a footer) that uses ONLY CSS variables โ€” no hardcoded colours anywhere.
  4. Add a toggle button that switches the data-theme attribute on <html> using one line of JavaScript: document.documentElement.dataset.theme = 'dark';
  5. The transition between themes should be smooth (add transition: background 0.3s, color 0.3s to body).

Lab 5: Complete Responsive Landing Page โ€” Meesho Clone

โฑ 60 minutesAdvanced

Objective: Build a complete, responsive landing page for an Indian e-commerce site using everything learned in this unit.

Requirements:

  1. Navbar (Flexbox): Logo, search bar (flex: 1), cart icon, profile icon. Collapses to hamburger menu on mobile.
  2. Hero Section: Full-width gradient background, centered text with clamp() font sizing, CTA button with hover animation.
  3. Category Bar (Flexbox): Horizontal scrollable category icons (Women, Men, Kids, Home, Beauty).
  4. Product Grid (CSS Grid): repeat(auto-fill, minmax(200px, 1fr)). Each card has image, title, price, discount badge, and hover lift effect.
  5. Footer (CSS Grid): 4-column layout with company info, links, social icons, and app download section. Collapses to 2-column on tablet, 1 on mobile.
  6. CSS Variables: Define all colours, fonts, spacing, and border-radii as variables.
  7. Animations: Fade-in on page load, hover effects on cards and buttons, loading spinner.
  8. Mobile-First: Start with mobile layout, add tablet and desktop media queries.

Deliverable: Two files โ€” meesho.html and meesho.css. No JavaScript except the mobile menu toggle.

Section 6

MCQ Assessment Bank โ€” 15 Questions

Hover over any question to reveal the answer. Each question is tagged with Bloom's Taxonomy level.

Q1

Which of the following has the HIGHEST CSS specificity?

  1. div p span
  2. .card .title
  3. #hero
  4. div.card p.title span.highlight
โœ… C. #hero โ€” Specificity: 1-0-0. An ID selector (1-0-0) always beats any combination of class (0-1-0) and type (0-0-1) selectors. Option D is 0-3-3, still less than 1-0-0.
L2 โ€” UnderstandSpecificity
Q2

What does * { box-sizing: border-box; } do?

  1. Makes all elements invisible
  2. Includes padding and border in the element's total width and height
  3. Removes all margins from elements
  4. Sets all elements to display: block
โœ… B. With border-box, width: 300px means the total width (content + padding + border) is 300px. Without it (default content-box), padding and border are added on top of the width.
L1 โ€” RememberBox Model
Q3

In Flexbox, which property aligns items along the CROSS axis?

  1. justify-content
  2. align-items
  3. flex-direction
  4. flex-wrap
โœ… B. align-items โ€” justify-content aligns along the main axis, align-items aligns along the cross axis. If flex-direction: row, main = horizontal, cross = vertical.
L1 โ€” RememberFlexbox
Q4

Which CSS Grid declaration creates a responsive grid that automatically wraps cards with a minimum width of 250px?

  1. grid-template-columns: 250px 250px 250px;
  2. grid-template-columns: repeat(3, 1fr);
  3. grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  4. grid-template-columns: auto auto auto;
โœ… C. repeat(auto-fill, minmax(250px, 1fr)) creates as many columns as will fit, each at least 250px wide, stretching to fill available space. This is self-responsive without media queries.
L3 โ€” ApplyCSS Grid
Q5

What is the correct way to define and use a CSS Variable?

  1. $primary: #6366f1; color: $primary;
  2. --primary: #6366f1; color: var(--primary);
  3. @primary: #6366f1; color: @primary;
  4. let primary = '#6366f1'; color: primary;
โœ… B. CSS Variables use the --name syntax for definition and var(--name) for usage. Option A is Sass syntax, C is Less syntax, D is JavaScript.
L1 โ€” RememberCSS Variables
Q6

A developer writes p { color: blue; } and .intro { color: red; }. A <p class="intro"> element will be:

  1. Blue โ€” type selector was written first
  2. Red โ€” class selector has higher specificity
  3. Blue โ€” p is more specific than .intro
  4. Neither โ€” the browser defaults to black
โœ… B. Class selector specificity (0-1-0) is higher than type selector specificity (0-0-1). The cascade resolves in favour of .intro, so the text is red.
L2 โ€” UnderstandSpecificity
Q7

Which pseudo-element is used to insert decorative content BEFORE an element?

  1. :before
  2. ::before
  3. :first-child
  4. ::first-line
โœ… B. ::before โ€” The double-colon :: is the modern syntax for pseudo-elements (CSS3). Single-colon :before still works but is legacy CSS2 syntax. ::before requires the content property to work.
L1 โ€” RememberPseudo-elements
Q8

In a mobile-first approach, which media query adds styles for desktop?

  1. @media (max-width: 1024px) { ... }
  2. @media (min-width: 1024px) { ... }
  3. @media screen and (width: 1024px) { ... }
  4. @media (device-width: 1024px) { ... }
โœ… B. Mobile-first means base styles are for mobile. min-width adds styles for screens at least 1024px wide (desktop). max-width is desktop-first (subtractive), which is the opposite approach.
L2 โ€” UnderstandResponsive
Q9

What does flex: 1 0 auto mean?

  1. The item cannot grow, cannot shrink, and uses its natural width
  2. The item will grow to fill space, will not shrink, and starts at its natural width
  3. The item is fixed at 1px wide
  4. The item is hidden
โœ… B. flex: grow shrink basis. flex: 1 0 auto means: grow factor = 1 (will grow to fill), shrink factor = 0 (won't shrink below basis), basis = auto (start at natural content width).
L2 โ€” UnderstandFlexbox
Q10

Which CSS property creates a smooth animation between hover states?

  1. animation
  2. transform
  3. transition
  4. @keyframes
โœ… C. transition โ€” Transitions animate changes between two states (e.g., normal โ†’ hover). animation and @keyframes are for multi-step animations that run continuously or on specific triggers. transform defines the transformation itself (rotate, scale, translate), not the animation.
L1 โ€” RememberTransitions
Q11

A Swiggy developer needs a 3-column footer on desktop that becomes 1-column on mobile. Which approach is MOST maintainable?

  1. Three separate <div> elements with float: left; width: 33.33%
  2. CSS Grid with repeat(auto-fit, minmax(250px, 1fr))
  3. Three <table> elements side by side
  4. JavaScript to dynamically change the layout
โœ… B. CSS Grid with auto-fit and minmax() is self-responsive โ€” no media queries needed. Floats (A) are deprecated for layouts, tables (C) are for tabular data, and JS layout changes (D) are unnecessary and fragile.
L5 โ€” EvaluateCSS Grid
Q12

Which of these correctly implements a CSS loading spinner?

  1. .spinner { animation: spin 1s linear infinite; } @keyframes spin { to { transform: rotate(360deg); } }
  2. .spinner { transition: rotate 1s; }
  3. .spinner { transform: rotate(360deg) infinite; }
  4. .spinner { @animate: spin 1s; }
โœ… A. A spinner requires @keyframes to define the rotation and animation to apply it infinitely. transition only works between two states (requires a trigger like hover). transform alone applies a static transformation without animation.
L3 โ€” ApplyAnimations
Q13

An element has width: 200px; padding: 20px; border: 5px solid; with default box-sizing. What is its rendered total width?

  1. 200px
  2. 240px
  3. 250px
  4. 245px
โœ… C. 250px โ€” Default box-sizing: content-box. Total = content (200) + left padding (20) + right padding (20) + left border (5) + right border (5) = 250px. With border-box, it would be 200px.
L3 โ€” ApplyBox Model
Q14

What does grid-template-areas: "header header" "sidebar main" "footer footer"; define?

  1. Three rows: header spans 2 columns, sidebar and main share row 2, footer spans 2 columns
  2. Two columns with three rows of equal height
  3. A 2ร—2 grid with overlapping areas
  4. An invalid CSS declaration
โœ… A. Each quoted string defines a row. Repeated names ("header header") mean that area spans multiple columns. This creates a classic Holy Grail layout with 3 rows and 2 columns.
L4 โ€” AnalyzeCSS Grid
Q15

Why should you include @media (prefers-reduced-motion: reduce) in your CSS?

  1. To make animations faster on low-end devices
  2. To disable animations for users who experience motion sickness โ€” an accessibility requirement
  3. To reduce CSS file size
  4. To support Internet Explorer
โœ… B. Some users have vestibular disorders and experience nausea from animations. prefers-reduced-motion respects their OS-level "Reduce motion" setting. This is a WCAG 2.1 AA requirement and a standard practice at Google, Apple, and every major tech company.
L5 โ€” EvaluateAccessibility
Section 7

Chapter Summary

๐ŸŽฏ Unit 3 โ€” Key Takeaways

  • CSS Rules = Selector + Declaration Block. Always use external stylesheets in production.
  • Selectors: Type, Class, ID, Attribute, Pseudo-class (:hover, :focus, :nth-child), Pseudo-element (::before, ::after).
  • Specificity: ID (1-0-0) > Class (0-1-0) > Type (0-0-1). Never use !important as a fix.
  • Box Model: Content โ†’ Padding โ†’ Border โ†’ Margin. Always use box-sizing: border-box.
  • Flexbox: One-dimensional layout. Use for navbars, card rows, centering. Key: display: flex, justify-content, align-items, gap.
  • CSS Grid: Two-dimensional layout. Use for page layouts, dashboards, product grids. Key: grid-template-columns, grid-template-areas, repeat(auto-fill, minmax()).
  • CSS Variables: Define in :root with --name, use with var(--name). Essential for theming and design systems.
  • Typography: Use Google Fonts, rem for font sizes, clamp() for responsive text.
  • Responsive: Mobile-first with min-width media queries. Breakpoints: 768px (tablet), 1024px (desktop).
  • Transitions: transition: property duration easing for smooth hover effects.
  • Animations: @keyframes + animation for complex multi-step animations.
  • Accessibility: Always include prefers-reduced-motion media query.

๐Ÿ“‹ CSS3 Quick Reference โ€” Copy-Paste Starter

/* === UNIVERSAL RESET === */
*, *::before, *::after { margin:0; padding:0; box-sizing:border-box; }

/* === VARIABLES === */
:root {
  --primary:#6366f1; --bg:#f8fafc; --text:#1e293b;
  --font:'Inter',sans-serif; --radius:12px;
}

/* === FLEXBOX CENTER === */
.flex-center { display:flex; justify-content:center; align-items:center; }

/* === AUTO-RESPONSIVE GRID === */
.auto-grid { display:grid; grid-template-columns:repeat(auto-fill,minmax(250px,1fr)); gap:20px; }

/* === SMOOTH TRANSITION === */
.smooth { transition:all 0.2s ease; }

/* === MOBILE-FIRST BREAKPOINTS === */
@media(min-width:768px)  { /* tablet */ }
@media(min-width:1024px) { /* desktop */ }
Section 8

Interview Preparation โ€” CSS Questions That Companies Ask

These are real questions asked at TCS, Infosys, Wipro, Flipkart, and startup interviews for frontend roles.

Q1: Explain the CSS Box Model. What is the difference between content-box and border-box?

Model Answer:

The CSS Box Model defines every element as a rectangular box with four layers: content (the actual text/image), padding (space inside the border), border (the visible edge), and margin (space outside the border).

With content-box (default), width applies only to the content area. Padding and border are added on top, making the total rendered width larger than specified. Example: width: 200px + padding: 20px + border: 5px = 250px total.

With border-box, width includes content + padding + border. width: 200px means 200px total, period. The content area shrinks to accommodate padding and border.

In production, we always use * { box-sizing: border-box } as the first rule โ€” it makes width calculations predictable.

Q2: What is CSS Specificity? How do you resolve specificity conflicts without using !important?

Model Answer:

Specificity is the algorithm browsers use to determine which CSS rule wins when multiple rules target the same element. It's calculated as a triplet: (ID, Class, Type).

  • ID selector (#hero): 1-0-0
  • Class selector (.card): 0-1-0
  • Type selector (div): 0-0-1

Higher specificity wins. If equal, the last rule in source order wins. To resolve conflicts without !important:

  1. Increase the specificity of your selector (e.g., .parent .card instead of .card)
  2. Use more specific class names (BEM methodology: .card__title)
  3. Restructure your CSS to avoid the conflict in the first place

!important should be avoided because it breaks the natural cascade, making future debugging extremely difficult.

Q3: When would you use Flexbox vs CSS Grid? Give real examples.

Model Answer:

Flexbox is one-dimensional โ€” it handles either a row or a column. Use it for:

  • Navigation bars (space-between logo and links)
  • Card content layout (icon + text side by side)
  • Centering elements (both vertically and horizontally)
  • Footer link groups

CSS Grid is two-dimensional โ€” it handles rows and columns simultaneously. Use it for:

  • Full page layouts (header, sidebar, main, footer)
  • Product grids with auto-fill and minmax()
  • Dashboard panels that need to be precisely positioned
  • Image galleries where items span multiple cells

They're complementary, not competing. A common pattern: Grid for the page layout, Flexbox for component-level alignment inside each grid cell.

Q4: How do you implement a dark mode toggle using only CSS?

Model Answer:

Define all colours as CSS Variables in :root. Create a second set of variables under a [data-theme="dark"] selector. Toggle the data-theme attribute on <html> with one line of JavaScript.

:root { --bg:#fff; --text:#1e293b; }
[data-theme="dark"] { --bg:#0f172a; --text:#e2e8f0; }
body { background:var(--bg); color:var(--text); transition:background .3s,color .3s; }

The key insight: zero component-level changes. Every component reads from variables, so the theme switch is global and instant. This is the pattern used by CRED, GitHub, and VS Code's web version.

Q5: What is "mobile-first" CSS? Why is it the industry standard?

Model Answer:

Mobile-first means writing base CSS for the smallest screen (mobile), then adding complexity for larger screens using min-width media queries.

It's the industry standard because:

  1. Performance: Mobile devices load only the base CSS. Desktop additions are layered on top.
  2. Priority: 70%+ of Indian web traffic is mobile (Flipkart, Swiggy, Meesho report this). Design for the majority first.
  3. Simplicity: It's easier to add complexity (desktop layouts) than to undo it (stripping desktop layouts for mobile).
  4. Progressive Enhancement: Every user gets a working experience. Larger screens get enhanced layouts.

The opposite (desktop-first with max-width queries) leads to "undoing" styles for mobile, which creates bloated CSS and maintenance headaches.