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
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.
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
<font> tags and <table> layouts. A single colour change required editing every page manually. CSS changed everything โ one stylesheet, one change, every page updated.Learning Outcomes โ Bloom's Taxonomy
| Bloom's Level | Learning Outcome |
|---|---|
| L1 โ Remember | Recall the syntax for CSS rules, selectors (type, class, id, attribute, pseudo-class, pseudo-element), and the box model components |
| L2 โ Understand | Explain how CSS specificity and the cascade determine which styles are applied when rules conflict |
| L3 โ Apply | Build responsive layouts using Flexbox and CSS Grid, apply Google Fonts, and implement CSS Variables for a design system |
| L4 โ Analyze | Debug layout issues using Chrome DevTools โ inspect computed box model, identify specificity conflicts, and diagnose overflow problems |
| L5 โ Evaluate | Compare Flexbox vs Grid for a given layout requirement and justify which approach is more maintainable and performant |
| L6 โ Create | Design and implement a complete, responsive, themed landing page for an Indian startup using CSS3, Flexbox, Grid, variables, and animations |
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
.css file and link it with <link>. Every company โ Flipkart, CRED, Google โ uses external stylesheets. This is non-negotiable.| Method | Syntax | Use Case | Industry? |
|---|---|---|---|
| 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 |
| Inline | style="color:red" on element | Quick overrides, dynamic JS styles | โ ๏ธ Avoid |
| @import | @import url('other.css'); inside CSS | Modular 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: 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
| Selector | Example | What it Selects | Specificity |
|---|---|---|---|
| Type | p | All <p> elements | 0-0-1 |
| Class | .card | All elements with class="card" | 0-1-0 |
| ID | #hero | The element with id="hero" | 1-0-0 |
| Attribute | [type="email"] | All inputs with type="email" | 0-1-0 |
| Pseudo-class | a:hover | Links on mouse hover | 0-1-0 |
| Pseudo-class | li:nth-child(odd) | Odd-numbered list items | 0-1-0 |
| Pseudo-class | input:focus | Currently focused input | 0-1-0 |
| Pseudo-element | p::first-line | First line of every paragraph | 0-0-1 |
| Pseudo-element | .card::before | Generated content before .card | 0-1-1 |
| Descendant | nav a | All <a> inside <nav> | 0-0-2 |
| Child | ul > li | Direct <li> children of <ul> | 0-0-2 |
| Universal | * | Everything | 0-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
/* width: 300px but ACTUAL width = 300 + 20 + 20 + 2 + 2 = 344px! */
.card {
width: 300px;
padding: 20px;
border: 2px solid #ccc;
/* Total width: 344px โ SURPRISE! ๐ฑ */
}
/* 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 โ
*/
}
* { 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.
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
| Property | Values | Effect |
|---|---|---|
flex-direction | row | column | row-reverse | column-reverse | Sets the main axis direction |
justify-content | flex-start | center | space-between | space-around | space-evenly | Alignment along main axis |
align-items | stretch | center | flex-start | flex-end | baseline | Alignment along cross axis |
flex-wrap | nowrap | wrap | wrap-reverse | Whether items wrap to next line |
gap | 16px | 1rem 2rem | Space between items (row-gap column-gap) |
flex | grow shrink basis | Shorthand: flex: 1 0 auto |
align-self | Same as align-items | Override 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
/* ๐ข 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
| Property | Example | Effect |
|---|---|---|
grid-template-columns | 200px 1fr 1fr | 3 columns: fixed + 2 flexible |
grid-template-rows | auto 1fr auto | Header, 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-fill | repeat(auto-fill, minmax(250px, 1fr)) | Auto-responsive grid |
gap | 16px 24px | Row gap & column gap |
grid-column | span 2 | Item spans 2 columns |
Flexbox vs Grid โ When to Use Which?
| Scenario | Use | Why |
|---|---|---|
| Navbar with logo + links | Flexbox | Single row, space-between |
| Product card grid | Grid | 2D layout, auto-fill responsive |
| Centering a modal | Flexbox | Simple 1D centering |
| Full page dashboard | Grid | Named areas, rows + columns |
| Card content (icon + text) | Flexbox | Single row alignment |
| Image gallery with spanning | Grid | Items 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;
}
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
| Unit | Base | Use Case | Example |
|---|---|---|---|
rem | Root font-size (16px) | Body text, headings โ scales globally | 1.5rem = 24px |
em | Parent's font-size | Padding relative to font size | padding: 0.5em |
px | Absolute pixel | Borders, shadows, precise control | border: 1px solid |
vw/vh | Viewport width/height | Hero sections, full-screen layouts | min-height: 100vh |
% | Parent element | Widths, max-width | width: 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.
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
| Device | Breakpoint | Common Use |
|---|---|---|
| Mobile (portrait) | 0 โ 480px | Single column, stacked layout |
| Mobile (landscape) / Small tablet | 481px โ 768px | 2-column grid, horizontal nav |
| Tablet / Small laptop | 769px โ 1024px | 3-column grid, sidebar visible |
| Desktop | 1025px โ 1440px | Full layout, max-width container |
| Large desktop / Ultrawide | 1441px+ | 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;
}
@media (prefers-reduced-motion: reduce) {
* {
animation-duration: 0.01ms !important;
transition-duration: 0.01ms !important;
}
}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";
}
}
Lab Exercises โ Hands-On Practice
Lab 1: CSS Selectors & Specificity Playground
Objective: Master CSS selectors by styling a restaurant menu page without modifying the HTML.
Instructions:
- Create
menu.htmlwith 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. - Create
menu.cssand style it using only these selector types:- Type selectors for base typography
- Class selectors for card styling
- Pseudo-class
:hoverfor 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
::beforeto add a โ icon before vegetarian items
- 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
Objective: Build a responsive navigation bar using Flexbox that matches Flipkart's layout.
Requirements:
- Create a navbar with: Logo (left), Search bar (center, flexible width), and User icons (right โ login, cart, more).
- Use
display: flex,justify-content: space-between,align-items: center. - The search bar should use
flex: 1to fill available space between logo and icons. - Add hover effects on nav links (underline slides in from left using
::afterpseudo-element +transition). - 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
Objective: Build a multi-panel dashboard layout using CSS Grid with named areas.
Requirements:
- Create a full-viewport layout with: Header (64px), Sidebar (250px), Main chart area (flexible), Watchlist panel (300px), Footer (40px).
- Use
grid-template-areaswith named areas: "header", "sidebar", "main", "watchlist", "footer". - Header and footer span all columns.
- Add a responsive breakpoint at 768px: collapse to single column, hide sidebar and watchlist.
- Style the sidebar with a dark background (#0f172a), the main area with a light background, and the watchlist with a slightly different shade.
- 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
Objective: Implement a complete theme system using CSS Variables with a dark/light mode toggle.
Requirements:
- Define a design system in
:rootwith variables for: colors (background, surface, text, primary, accent), spacing (4 sizes), border-radius (3 sizes), and fonts. - Create a
[data-theme="dark"]and[data-theme="light"]selector that overrides the colour variables. - Build a simple card-based UI (3 cards, a header, and a footer) that uses ONLY CSS variables โ no hardcoded colours anywhere.
- Add a toggle button that switches the
data-themeattribute on<html>using one line of JavaScript:document.documentElement.dataset.theme = 'dark'; - The transition between themes should be smooth (add
transition: background 0.3s, color 0.3stobody).
Lab 5: Complete Responsive Landing Page โ Meesho Clone
Objective: Build a complete, responsive landing page for an Indian e-commerce site using everything learned in this unit.
Requirements:
- Navbar (Flexbox): Logo, search bar (flex: 1), cart icon, profile icon. Collapses to hamburger menu on mobile.
- Hero Section: Full-width gradient background, centered text with
clamp()font sizing, CTA button with hover animation. - Category Bar (Flexbox): Horizontal scrollable category icons (Women, Men, Kids, Home, Beauty).
- Product Grid (CSS Grid):
repeat(auto-fill, minmax(200px, 1fr)). Each card has image, title, price, discount badge, and hover lift effect. - 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.
- CSS Variables: Define all colours, fonts, spacing, and border-radii as variables.
- Animations: Fade-in on page load, hover effects on cards and buttons, loading spinner.
- 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.
MCQ Assessment Bank โ 15 Questions
Hover over any question to reveal the answer. Each question is tagged with Bloom's Taxonomy level.
Which of the following has the HIGHEST CSS specificity?
div p span.card .title#herodiv.card p.title span.highlight
#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.What does * { box-sizing: border-box; } do?
- Makes all elements invisible
- Includes padding and border in the element's total width and height
- Removes all margins from elements
- Sets all elements to display: block
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.In Flexbox, which property aligns items along the CROSS axis?
justify-contentalign-itemsflex-directionflex-wrap
align-items โ justify-content aligns along the main axis, align-items aligns along the cross axis. If flex-direction: row, main = horizontal, cross = vertical.Which CSS Grid declaration creates a responsive grid that automatically wraps cards with a minimum width of 250px?
grid-template-columns: 250px 250px 250px;grid-template-columns: repeat(3, 1fr);grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));grid-template-columns: auto auto auto;
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.What is the correct way to define and use a CSS Variable?
$primary: #6366f1; color: $primary;--primary: #6366f1; color: var(--primary);@primary: #6366f1; color: @primary;let primary = '#6366f1'; color: primary;
--name syntax for definition and var(--name) for usage. Option A is Sass syntax, C is Less syntax, D is JavaScript.A developer writes p { color: blue; } and .intro { color: red; }. A <p class="intro"> element will be:
- Blue โ type selector was written first
- Red โ class selector has higher specificity
- Blue โ
pis more specific than.intro - Neither โ the browser defaults to black
.intro, so the text is red.Which pseudo-element is used to insert decorative content BEFORE an element?
:before::before:first-child::first-line
::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.In a mobile-first approach, which media query adds styles for desktop?
@media (max-width: 1024px) { ... }@media (min-width: 1024px) { ... }@media screen and (width: 1024px) { ... }@media (device-width: 1024px) { ... }
min-width adds styles for screens at least 1024px wide (desktop). max-width is desktop-first (subtractive), which is the opposite approach.What does flex: 1 0 auto mean?
- The item cannot grow, cannot shrink, and uses its natural width
- The item will grow to fill space, will not shrink, and starts at its natural width
- The item is fixed at 1px wide
- The item is hidden
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).Which CSS property creates a smooth animation between hover states?
animationtransformtransition@keyframes
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.A Swiggy developer needs a 3-column footer on desktop that becomes 1-column on mobile. Which approach is MOST maintainable?
- Three separate
<div>elements withfloat: left; width: 33.33% - CSS Grid with
repeat(auto-fit, minmax(250px, 1fr)) - Three
<table>elements side by side - JavaScript to dynamically change the layout
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.Which of these correctly implements a CSS loading spinner?
.spinner { animation: spin 1s linear infinite; } @keyframes spin { to { transform: rotate(360deg); } }.spinner { transition: rotate 1s; }.spinner { transform: rotate(360deg) infinite; }.spinner { @animate: spin 1s; }
@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.An element has width: 200px; padding: 20px; border: 5px solid; with default box-sizing. What is its rendered total width?
- 200px
- 240px
- 250px
- 245px
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.What does grid-template-areas: "header header" "sidebar main" "footer footer"; define?
- Three rows: header spans 2 columns, sidebar and main share row 2, footer spans 2 columns
- Two columns with three rows of equal height
- A 2ร2 grid with overlapping areas
- An invalid CSS declaration
Why should you include @media (prefers-reduced-motion: reduce) in your CSS?
- To make animations faster on low-end devices
- To disable animations for users who experience motion sickness โ an accessibility requirement
- To reduce CSS file size
- To support Internet Explorer
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.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
!importantas 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
:rootwith--name, use withvar(--name). Essential for theming and design systems. - Typography: Use Google Fonts,
remfor font sizes,clamp()for responsive text. - Responsive: Mobile-first with
min-widthmedia queries. Breakpoints: 768px (tablet), 1024px (desktop). - Transitions:
transition: property duration easingfor smooth hover effects. - Animations:
@keyframes+animationfor complex multi-step animations. - Accessibility: Always include
prefers-reduced-motionmedia 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 */ }
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:
- Increase the specificity of your selector (e.g.,
.parent .cardinstead of.card) - Use more specific class names (BEM methodology:
.card__title) - 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-fillandminmax() - 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:
- Performance: Mobile devices load only the base CSS. Desktop additions are layered on top.
- Priority: 70%+ of Indian web traffic is mobile (Flipkart, Swiggy, Meesho report this). Design for the majority first.
- Simplicity: It's easier to add complexity (desktop layouts) than to undo it (stripping desktop layouts for mobile).
- 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.