Complete CSS Progressive Interview Question Bank
50 progressive CSS interview questions complete with technical explanations, key takeaways, diagrams, code examples, and interactive knowledge check quizzes.
Q1: What are the core components of a CSS rule?
A CSS rule consists of a Selector (targeting the HTML DOM node) and a Declaration Block enclosed in curly braces {}. Inside the block, declarations are written as property: value; pairs separated by semicolons.
/* Selector { Property: Value; } */
h1 {
color: #2965f1;
font-size: 2rem;
}h1 targets heading tags, setting text color to hex #2965f1 and font size to 2rem.
Selector identifies the DOM element node.
Declaration block contains property and value pairs.
In the declaration font-size: 16px;, what is 'font-size' called?
Q2: What are the four layers of the standard CSS Box Model?
Every rendered HTML element is enclosed in a rectangular box consisting of four concentric layers from inside out: Content, Padding (transparent area inside borders), Border (outer edge surrounding padding), and Margin (transparent clearance separating neighbor elements).
.box {
width: 200px; /* Content Area */
padding: 20px; /* Inner clearance */
border: 2px solid; /* Enclosing boundary */
margin: 15px; /* Outer clearance */
}These four properties define the complete spatial geometry of the HTML box element.
Layers from inside out: Content → Padding → Border → Margin.
Padding adds space inside the border; Margin creates clearance outside.
Which Box Model layer creates clearance inside an element's border?
Q3: What is the difference between content-box and border-box sizing?
In content-box (browser default), declared width and height apply strictly to content. Padding and border add onto the width, expanding total rendered size (width + padding + border). In border-box, padding and border are included inside the defined width.
*, *::before, *::after {
box-sizing: border-box;
}
.card {
width: 300px;
padding: 20px;
border: 5px solid black;
/* Total width remains exactly 300px with border-box */
}border-box prevents elements from breaking layouts when padding or borders are added.
content-boxexpands total element dimensions when padding or border is added.border-boxlocks overall dimensions, fitting padding and border inside width.
What is the total computed pixel width of an element with width: 100px, padding: 10px, border: 2px, and box-sizing: content-box?
Q4: How do display: block, inline, and inline-block differ?
block: Starts on a new line, expands to fill 100% container width, and respects width/height.inline: Flows within text, occupies required content width, and ignores top/bottom margins and width/height.inline-block: Flows inline like text, but honors explicit width, height, padding, and margins.
.badge {
display: inline-block;
width: 80px;
height: 24px;
padding: 4px;
}inline-block keeps items inline with surrounding text while respecting explicit width and height.
inlineelements ignore vertical margins and explicit width/height dimensions.inline-blockflows side-by-side while preserving explicit dimension control.
Which display value allows setting explicit width and height while flowing elements inline on the same line?
Q5: How is CSS Specificity calculated?
Specificity is calculated as a 3-column vector score: IDs (1,0,0), Classes / Attributes / Pseudo-classes (0,1,0), and Elements / Pseudo-elements (0,0,1). Inline styles carry (1,0,0,0) weight. !important bypasses standard specificity weight comparisons entirely.
/* Score: (0,0,1) */
p { color: black; }
/* Score: (0,1,1) */
p.highlight { color: blue; }
/* Score: (1,0,0) - Wins over class selectors */
#main-content { color: red; }#main-content wins because its ID score (1,0,0) outweighs class and tag scores.
Specificity hierarchy: Inline Styles > IDs > Classes/Attributes/Pseudo-classes > Elements.
Equal specificity rules resolve by giving precedence to whichever rule appears last in stylesheet order.
Which selector carries the highest calculated specificity score?
Q6: What is Margin Collapse and when does it occur?
Margin collapse happens when top and bottom margins of adjacent block elements combine into a single merged margin whose size equals the largest individual margin. It occurs between adjacent vertical siblings, parent and first/last child, or empty blocks.
.box1 {
margin-bottom: 30px;
}
.box2 {
margin-top: 20px;
}
/* Rendered clearance between box1 and box2 is 30px (not 50px) */Vertical sibling margins collapse, adopting the larger 30px value instead of summing them.
Only vertical (top/bottom) margins collapse; horizontal margins never collapse.
Creating a new Block Formatting Context (BFC) prevents parent-child margin collapse.
What is the final vertical margin gap between two siblings where item 1 has margin-bottom: 40px and item 2 has margin-top: 25px?
Q7: What is the difference between rem, em, vh, and vw units?
rem(Root EM): Relative to font-size of the root<html>element (default 16px).em: Relative to font-size of the parent or local element (compounds on nested elements).vh/vw: Percentage of viewport height / width (1vh = 1% viewport height).
html {
font-size: 16px;
}
.card {
font-size: 1.25rem; /* 20px */
padding: 1em; /* 20px (relative to card's own font-size) */
}rem references the root html font-size, while em calculates based on local font-size.
remensures consistent scaling relative to root html font configuration.emscales relative to immediate parent font size and compounds when nested.
If root html has font-size: 16px, what is the calculated value of 2.5rem?
Q8: How do static, relative, absolute, fixed, and sticky positioning modes work?
static: Default document flow.relative: Shifted relative to normal flow position without affecting neighboring layout.absolute: Positioned relative to nearest non-static positioned ancestor.fixed: Positioned relative to the viewport window.sticky: Switches between relative and fixed based on user scroll position thresholds.
.header {
position: sticky;
top: 0;
background: white;
z-index: 1000;
}Sticky switches from relative flow to fixed positioning when scrolling hits top: 0 boundary.
absolutealigns relative to nearest non-static positioned ancestor.stickyanchors elements relative to scroll container bounds.
Against what reference frame does an element with position: absolute position itself?
Q9: How do Flexbox axes operate and what are primary flex container properties?
Flexbox manages 1-dimensional layouts along two axes: Main Axis (defined by flex-direction: row or column) and Cross Axis (perpendicular to main axis). Container rules include display: flex, flex-direction, and flex-wrap.
.flex-parent {
display: flex;
flex-direction: row;
flex-wrap: wrap;
}Establishes a horizontal main axis with multi-line item wrapping enabled.
flex-directiondictates whether main axis runs horizontally or vertically.flex-wrap: wrapallows flex items to flow onto additional lines.
If flex-direction is set to column, which orientation does the Cross Axis adopt?
Q10: What is the difference between justify-content, align-items, and align-content?
justify-content: Aligns flex items along the main axis.align-items: Aligns flex items along the cross axis within a single line.align-content: Distributes multi-line flex tracks along the cross axis whenflex-wrap: wrapis enabled.
.center-box {
display: flex;
justify-content: center; /* Main axis center */
align-items: center; /* Cross axis center */
height: 100vh;
}Combines justify-content and align-items to center content vertically and horizontally.
justify-contentmanages main-axis distribution.align-itemsaligns individual items inside flex lines on cross axis.align-contenttargets track spacing across wrapped multi-line containers.
Which Flexbox property distributes wrapped track rows along the cross axis?
Q11: How do flex-grow, flex-shrink, and flex-basis operate in flex shorthand?
flex-grow: Ratio dictating how much item expands to fill remaining space.flex-shrink: Ratio dictating how much item shrinks when total size exceeds container.flex-basis: Initial baseline size of item before grow/shrink space distribution. Shorthand:flex: <grow> <shrink> <basis>.
.flex-grow-item {
flex: 1; /* flex: 1 1 0% */
}
.flex-fixed-item {
flex: 0 0 250px; /* Fixed 250px width */
}flex: 0 0 250px locks column width, preventing growth or shrinking.
flex: 1expands toflex: 1 1 0%, forcing equal size distribution.flex: 0 0 200pxlocks item to fixed 200px dimension.
What does setting flex: 0 0 200px achieve on a flex child?
Q12: How do grid-template-columns and grid-template-rows define CSS Grid layouts?
CSS Grid defines two-dimensional layouts using grid-template-columns and grid-template-rows. Tracks accept pixel lengths, percentages, viewport units, or responsive fractional length units (fr).
.grid-container {
display: grid;
grid-template-columns: 200px 1fr 1fr;
grid-template-rows: 80px auto;
gap: 16px;
}Creates a 3-column grid where column 1 is 200px fixed, and remaining space splits between columns 2 and 3.
CSS Grid manages two-dimensional spatial layouts simultaneously.
grid-template-columnsandgrid-template-rowsestablish layout matrices.
Which property defines the explicit horizontal column layout matrix in CSS Grid?
Q13: How does the fr (Fractional) unit work in CSS Grid?
The fr unit represents a fraction of available free space in grid containers. Free space is calculated after allocating fixed pixel or percentage dimensions, allowing responsive grid columns to expand and contract proportionally.
.grid {
display: grid;
/* Column 1 takes 200px; remaining space splits 1:2 between columns 2 and 3 */
grid-template-columns: 200px 1fr 2fr;
}After allocating 200px, remaining space splits into 3 parts: col 2 gets 1/3, col 3 gets 2/3.
frdistributes remaining unallocated space inside grid containers.Combines seamlessly with
repeat()andminmax()functions.
In a 900px wide grid with grid-template-columns: 1fr 2fr, how wide is the second column?
Q14: What is the fundamental difference between Flexbox and CSS Grid?
Flexbox is designed for one-dimensional layouts (aligning items along either a row OR a column). CSS Grid is designed for two-dimensional layouts (simultaneously managing rows AND columns). Flexbox is content-driven, whereas Grid is layout-driven.
/* 1D Flexbox Row */
.flex-row {
display: flex;
justify-content: space-between;
}
/* 2D Grid Matrix */
.grid-matrix {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 20px;
}Flexbox aligns items along a single row, whereas Grid builds structured row and column matrices.
Flexbox manages 1D axis layouts (row OR column).
CSS Grid manages 2D spatial layouts (rows AND columns).
Which layout engine is optimized for managing rows and columns simultaneously?
Q15: What is a Block Formatting Context (BFC) and how is one created?
A Block Formatting Context (BFC) is an isolated visual CSS rendering region where block boxes are laid out. BFCs contain internal floats, prevent margin collapsing with descendants, and prevent text wrapping around floats. Created via display: flow-root, overflow: hidden, display: flex, or grid.
.container {
/* Modern, side-effect free BFC creation */
display: flow-root;
/* Contains internal float elements cleanly */
}display: flow-root establishes a BFC that safely encloses float elements.
Isolates visual element layout rules from external document context.
display: flow-rootis the modern CSS standard for creating a clean BFC.
Which property creates a clean Block Formatting Context without layout side-effects?
Q16: How do CSS Custom Properties (Variables) differ from preprocessor variables (Sass)?
CSS Custom Properties (--var-name) are native runtime DOM variables evaluated live in the browser. They inherit down the cascade, react dynamically to media queries, and can be read/modified using JavaScript. Preprocessor variables (Sass $var) are static and compiled at build time.
:root {
--main-bg: #ffffff;
--text-color: #111111;
}
@media (prefers-color-scheme: dark) {
:root {
--main-bg: #121212;
--text-color: #ffffff;
}
}
body {
background-color: var(--main-bg);
color: var(--text-color);
}Browsers automatically re-evaluate CSS variables when dark mode media queries trigger.
Native CSS variables dynamically inherit and adapt to runtime media query changes.
Can be read and updated live using JavaScript
setProperty().
What happens when a CSS custom property value changes inside a media query rule at runtime?
Q17: How do Media Queries (@media) structure mobile-first responsive architecture?
Mobile-first responsive design defines base styles for small screens first, then uses @media (min-width: ...) queries to layer on layout enhancements as viewport width increases.
/* Base Styles (Mobile) */
.grid {
display: block;
}
/* Tablet Breakpoint */
@media (min-width: 768px) {
.grid {
display: grid;
grid-template-columns: repeat(2, 1fr);
}
}
/* Desktop Breakpoint */
@media (min-width: 1024px) {
.grid {
grid-template-columns: repeat(4, 1fr);
}
}Layout rules progressively enhance from single column to 2 and 4 columns as screens widen.
min-widthqueries build progressive enhancements from small to large viewports.Mobile-first architectures minimize stylesheet overrides.
Which query type forms the foundation of Mobile-First responsive CSS architectures?
Q18: What is the difference between CSS Transitions and CSS Keyframe Animations?
- Transitions: Smoothly interpolate property changes between two states (e.g., initial to
:hover). Require an explicit state trigger. - Animations (@keyframes): Complex multi-step state sequences running automatically on page load or trigger, supporting infinite loops and keyframe steps.
/* Transition on hover */
.btn {
transition: transform 0.2s ease;
}
.btn:hover { transform: scale(1.05); }
/* Keyframe loop animation */
@keyframes pulse {
0% { opacity: 1; }
50% { opacity: 0.5; }
100% { opacity: 1; }
}
.spinner {
animation: pulse 1.5s infinite;
}Transitions react to hover interactions; keyframe animations run autonomous loops.
Transitions interpolate state changes between 2 points (A → B).
Animations (@keyframes) execute multi-step keyframe sequences.
Which feature allows setting intermediate animation states at 25%, 50%, and 75% intervals?
Q19: How do transform functions alter element visual layout without triggering reflows?
transform functions (translate, scale, rotate, skew) alter visual geometric rendering without modifying element box model dimensions or affecting surrounding layout flow, avoiding expensive CPU reflow calculations.
.card-hover {
transition: transform 0.3s ease;
}
.card-hover:hover {
transform: translateY(-8px) scale(1.05);
}translateY and scale provide GPU-accelerated hover effects without disturbing adjacent cards.
Transforms modify visual rendering without triggering document layout reflows.
translate()positioning is GPU-accelerated.
Does applying transform: translateY(-20px) shift the layout position of adjacent sibling elements?
Q20: How do Stacking Contexts affect z-index ordering?
An element's z-index layer ordering operates strictly within its active Stacking Context. A child element with z-index: 9999 inside a parent with z-index: 1 will never stack above a neighboring parent with z-index: 2. Stacking contexts are created by opacity < 1, transform properties, filter effects, or setting isolation: isolate.
.card {
isolation: isolate; /* Establishes isolated stacking boundary */
}
.card-badge {
position: absolute;
z-index: 10; /* Contained inside .card stacking context */
}isolation: isolate prevents child z-index values from leaking into global page layout stacks.
z-indexcomparisons occur strictly within shared stacking contexts.isolation: isolatecreates a clean isolated stacking context.
Which property safely isolates descendant z-index layers into a new stacking context?
Q21: How do clamp(), min(), and max() functions enable fluid responsive design?
clamp(MIN, VAL, MAX): Constrains a value within lower and upper bounds.min(VAL1, VAL2): Selects the smallest value.max(VAL1, VAL2): Selects the largest value. They enable fluid typography scaling without writing explicit media queries.
h1 {
/* Minimum: 2rem, Preferred: 5vw, Maximum: 4rem */
font-size: clamp(2rem, 5vw, 4rem);
}Heading text scales dynamically with viewport width, constrained safely between 2rem and 4rem.
clamp()sets fluid values that scale between minimum and maximum bounds.Reduces reliance on explicit
@mediaquery breakpoint rules.
What is the computed output of font-size: clamp(16px, 10px, 24px)?
Q22: What is the :has() parent pseudo-class selector in CSS?
The :has() pseudo-class (known as the CSS parent selector) selects parent elements based on whether they contain specific descendant elements or matching state selectors (e.g., card:has(img) or form:has(:invalid)).
/* Styles form when any child input is invalid */
form:has(input:invalid) {
border: 2px solid red;
}
/* Styles cards containing hero images */
.card:has(img.hero) {
grid-column: span 2;
}:has checks child presence and updates parent container styles dynamically.
Acts as a relational CSS parent selector.
Styles containers based on descendant child elements or active form states.
Which selector targets an <a> anchor tag only when it contains an internal <img> tag?
Q23: What problem does CSS Subgrid solve in nested grid components?
grid-template-columns: subgrid or grid-template-rows: subgrid allows nested child grids to inherit track alignments defined on parent grids, enabling card headers, bodies, and footers across adjacent grid cards to align perfectly.
.parent-grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
}
.card {
display: grid;
grid-template-rows: subgrid;
grid-row: span 3;
}Subgrid forces card headers, bodies, and footers across neighboring cards to align along parent row lines.
Nested grid components share parent column and row track lines.
Aligns nested headers, bodies, and footers across adjacent cards.
What primary layout capability does subgrid provide?
Q24: How do Container Queries (@container) differ from Media Queries (@media)?
Media Queries (@media) evaluate global viewport browser dimensions. Container Queries (@container) evaluate the width/size of direct parent containers, allowing components to adjust layouts based on local available space.
/* 1. Establish container context on parent */
.card-wrapper {
container-type: inline-size;
container-name: card-container;
}
/* 2. Style component based on parent width */
@container card-container (min-width: 400px) {
.card {
display: flex;
}
}The card component switches to flex layout whenever its parent wrapper expands beyond 400px.
@mediaqueries monitor global viewport dimensions.@containerqueries adapt component layouts to local parent element sizes.
What CSS property must be applied to a parent element to enable descendant container queries?
Q25: What are CSS Cascade Layers (@layer) and how do they manage priority?
Cascade Layers (@layer) allow developers to control CSS override priority explicitly regardless of selector specificity. Code defined in later layers takes precedence over earlier layers. Unlayered styles always override layered styles.
/* Establish layer priority order */
@layer reset, base, components, utilities;
@layer components {
#widget .btn { background: red; }
}
@layer utilities {
.bg-green { background: green; }
}The utilities layer takes precedence over components, overriding background color despite lower class specificity.
Defines explicit order of precedence across design system stylesheets.
Unlayered CSS rules always override layered selectors.
Which CSS rule takes priority when conflicting layer definitions exist?
Q26: What is GPU Hardware Acceleration in CSS animations and how is it triggered?
Hardware acceleration offloads animation rendering from CPU to GPU. CPU rendering triggers expensive Layout and Paint operations. GPU acceleration targets compositor properties (transform, opacity, filter), ensuring 60fps performance.
.animated-box {
will-change: transform, opacity;
transition: transform 0.3s ease;
}
.animated-box:hover {
transform: translateY(-10px) scale(1.05);
}Animating transform avoids triggering layout reflows, delegating operations to GPU rendering layers.
Animates GPU composited properties (
transform,opacity) to avoid reflow/paint passes.will-changesignals render engines to prepare GPU layer acceleration.
Which set of CSS properties can be animated without triggering CPU Layout or Paint rendering passes?
Q27: What is the difference between auto-fill and auto-fit in CSS Grid repeat()?
Both auto-generate column tracks. When extra grid space exists:
auto-fill: Retains empty invisible column tracks, keeping grid item sizes fixed.auto-fit: Collapses empty tracks to 0px, stretching existing grid items across the full container width.
.responsive-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 1rem;
}auto-fit automatically recalculates grid columns to fill row space without requiring media queries.
auto-fillpreserves empty grid column tracks.auto-fitcollapses empty space and expands existing grid items to fill full container width.
Which keyword collapses empty grid column tracks and stretches active items across container widths?
Q28: How does content-visibility: auto optimize page rendering performance?
content-visibility: auto skips rendering (layout and painting) for off-screen elements until the user scrolls near them, speeding up initial page loads on long web pages.
.long-section {
content-visibility: auto;
contain-intrinsic-size: 0 500px;
}Off-screen sections skip layout rendering until scrolled near the active viewport.
Skips rendering calculations for off-screen element subtrees.
Reduces initial page rendering times on long scrollable pages.
What is the function of contain-intrinsic-size when paired with content-visibility: auto?
Q29: How does native CSS Nesting work and what syntax rules apply?
Native CSS nesting allows nesting child rules inside parent selectors directly in modern browser stylesheets without requiring preprocessors. The & nesting selector explicitly references parent elements.
.card {
background: white;
padding: 1rem;
& .title {
font-size: 1.5rem;
}
&:hover {
box-shadow: 0 4px 12px rgba(0,0,0,0.1);
}
}Nesting child selectors and hover states directly inside parent blocks mirrors Sass workflows natively.
Supported natively in modern browsers without preprocessor compilation.
&represents parent selector combinations.
What character represents the parent selector inside native CSS nesting blocks?
Q30: How does the aspect-ratio property prevent Cumulative Layout Shift (CLS)?
The aspect-ratio property defines desired width-to-height ratio dimensions (e.g., 16 / 9) for layout boxes. Reserving container dimensions before media assets finish loading prevents sudden layout shifts, directly lowering Cumulative Layout Shift (CLS).
.video-container {
width: 100%;
aspect-ratio: 16 / 9;
background-color: #f0f0f0;
}The container maintains a 16:9 proportion automatically relative to width adjustments, reserving screen layout space.
Reserves explicit layout box proportions prior to media asset loading.
Prevents Cumulative Layout Shift (CLS) layout disruptions.
Which Core Web Vital metric is improved by setting CSS aspect-ratio on responsive media wrappers?