Chapter 59
Interview Prep
25 min read
CSS
CSS Interview Questions — Top 40 with Answers
The 40 most frequently asked CSS interview questions, organized into five themed groups: fundamentals, box model & layout basics, flexbox & grid, positioning & specificity, and modern CSS. Every answer is written the way you'd actually want to explain it out loud in an interview — clear, complete, and focused on the "why," not just the "what."
1
CSS Fundamentals
Questions 1–8
CSS (Cascading Style Sheets) is the language used to describe
the visual presentation of HTML — colours, layout, spacing,
typography, animation — separating content (HTML) from
presentation (CSS).
Three ways to apply CSS:
— Inline:
— Internal: a
— External: a separate
Three ways to apply CSS:
— Inline:
style="color:red" directly
on an HTML element. Highest priority but hardest to
maintain.— Internal: a
<style> block inside
the document's
<head>. Useful for
single-page demos, but doesn't scale to multiple pages.— External: a separate
.css file linked via
<link rel="stylesheet">. The standard approach for real projects — cacheable,
reusable across pages, and keeps markup clean.
"Cascading" refers to the algorithm the browser uses to
resolve conflicts when multiple CSS rules target the same
element with competing values. Rather than picking one rule
arbitrarily, the cascade follows a defined order of
precedence: first by origin and importance (user-agent styles,
then author styles, then
This layered, rule-based resolution — water "cascading" down through several decision tiers before settling on a final value — is what gives the language its name. Understanding the cascade order is essential for debugging "why isn't my CSS working" issues.
!important rules), then by
specificity (ID beats class beats element), and finally by
source order (later rules win ties).This layered, rule-based resolution — water "cascading" down through several decision tiers before settling on a final value — is what gives the language its name. Understanding the cascade order is essential for debugging "why isn't my CSS working" issues.
A class (
An ID (
.classname) can be applied to multiple elements on the same page, and a
single element can have multiple classes. Classes are the
standard way to style reusable components.An ID (
#idname) is meant to be unique — only one element per page should
have a given ID. IDs also have much higher specificity than
classes, making them harder to override later, which is why
most style guides recommend using classes for styling and
reserving IDs for JavaScript hooks or anchor links instead.
— Absolute units (
— Relative units (
— Viewport units (
Modern responsive design typically favours relative and viewport units over fixed pixels for anything that should scale across screen sizes — though
px) are fixed regardless of context — 1px is always the same
size relative to the screen's pixel density.— Relative units (
%, em,
rem) scale based on
something else — a percentage of the parent, the parent's
font-size, or the root font-size respectively.— Viewport units (
vw, vh,
vmin,
vmax) scale based on the
browser window's dimensions — 1vw is always 1% of the viewport
width.Modern responsive design typically favours relative and viewport units over fixed pixels for anything that should scale across screen sizes — though
px remains common for
borders and fine details where exact pixel control matters.
em is relative to the
font-size of the element's OWN PARENT. This means em values
compound through nesting — if a parent has
font-size: 1.2em and a
child also has
font-size: 1.2em, the
child's actual rendered size is 1.2 × 1.2 × the root size, not
simply 1.2×. Deeply nested elements using em can produce
unpredictable, escalating sizes.rem is always relative to
the ROOT
<html> element's
font-size, regardless of how deeply nested the element is.
1.2rem means the same
thing everywhere in the document.Because of this predictability, most projects default to
rem for font sizes and
spacing, reserving em for
specific cases where you deliberately want sizing to scale
with a local parent context (like icon sizes that should match
adjacent text).
— block: takes up the full available width by
default, starts on a new line, and respects
width/height/margin/padding on all four sides. Examples:
— inline: only takes up as much width as its content needs, sits inline with surrounding text/elements without forcing a line break, and IGNORES width/height and top/bottom margin. Examples:
— inline-block: a hybrid — flows inline like text (doesn't force a new line) but respects width, height, and margin on all sides like a block element. Commonly used for nav links or buttons that need explicit sizing but should sit in a row.
div,
p,
section.— inline: only takes up as much width as its content needs, sits inline with surrounding text/elements without forcing a line break, and IGNORES width/height and top/bottom margin. Examples:
span,
a,
strong.— inline-block: a hybrid — flows inline like text (doesn't force a new line) but respects width, height, and margin on all sides like a block element. Commonly used for nav links or buttons that need explicit sizing but should sit in a row.
A pseudo-class (single colon,
A pseudo-element (double colon,
The double-colon syntax for pseudo-elements was introduced in CSS3 to visually distinguish them from pseudo-classes, though single-colon
:hover,
:focus,
:nth-child()) selects an
element based on a STATE or POSITION it's currently in — being
hovered, being the third child, being checked — without
needing extra markup or classes.A pseudo-element (double colon,
::before,
::after,
::placeholder) creates or
targets a sub-part of an element that doesn't exist as a real
DOM node — ::before and
::after insert generated
content, while
::placeholder targets the
placeholder text inside an input.The double-colon syntax for pseudo-elements was introduced in CSS3 to visually distinguish them from pseudo-classes, though single-colon
:before/:after
is still supported for backward compatibility with CSS2.
The universal selector
Performance-wise, on modern browsers a single universal selector reset is not a meaningful concern — browsers are heavily optimised for this common pattern. The actual performance issue arises with OVERLY BROAD compound selectors that combine the universal selector with deep descendant chains, like
* matches every single
element in the document. It's most commonly used in CSS
resets:
* { margin: 0; padding: 0; box-sizing: border-box; }
applies consistent baseline values across all elements in one
declaration.Performance-wise, on modern browsers a single universal selector reset is not a meaningful concern — browsers are heavily optimised for this common pattern. The actual performance issue arises with OVERLY BROAD compound selectors that combine the universal selector with deep descendant chains, like
* * * { } or
.container * .item, which
can force the browser to check far more elements than
necessary during selector matching. In practice, a simple
* reset at the top of a
stylesheet is a completely standard and safe pattern.
2
Box Model & Layout Basics
Questions 9–16
The box model describes how every HTML element's total
rendered size is calculated, from the inside out, across four
layers:
1. Content — the actual text/image content, sized by width and height
2. Padding — space between the content and the border, inside the element
3. Border — a visible (or invisible) line around the padding
4. Margin — space outside the border, separating this element from its neighbours
By default (
1. Content — the actual text/image content, sized by width and height
2. Padding — space between the content and the border, inside the element
3. Border — a visible (or invisible) line around the padding
4. Margin — space outside the border, separating this element from its neighbours
By default (
box-sizing: content-box), the width and
height properties apply
ONLY to the content layer — padding and border get added on
top, making the element's actual rendered size larger than the
declared width. This frequently causes layout surprises, which
is why most modern projects set
box-sizing: border-box
globally, making width/height include padding and border for
far more predictable sizing.
content-box (the default):
width: 200px means the
CONTENT area is exactly 200px. Padding and border are added on
top, so an element with 20px padding and a 2px border actually
renders at 244px total width (200 + 20×2 + 2×2).border-box:
width: 200px means the
TOTAL rendered box (content + padding + border) is exactly
200px. The browser automatically shrinks the content area to
make room for padding and border within that fixed total.border-box is almost
universally preferred in real projects because it makes width
calculations predictable — if you set something to 25% width
in a 4-column layout, it stays exactly 25% regardless of
padding/border, which isn't true with content-box.
Margin collapse happens when two VERTICAL margins meet —
either between adjacent sibling block elements, or between a
parent and its first/last child with no border/padding/content
separating them. Instead of adding the two margins together,
the browser collapses them into a SINGLE margin equal to the
larger of the two values.
Example: if element A has
Common ways to prevent it: add padding or a border to the parent (even 1px), give the parent
Example: if element A has
margin-bottom: 20px and
the next sibling B has
margin-top: 30px, the
actual gap between them is 30px (the larger value), not 50px
(their sum) — many developers expect summation and are
surprised by this.Common ways to prevent it: add padding or a border to the parent (even 1px), give the parent
overflow: hidden or use a
flex/grid container (margin collapse doesn't apply to
flex/grid children), or use only one of the two margins (e.g.,
only `margin-bottom` on items, never `margin-top` too) for
consistent, predictable spacing.
display: none removes the
element entirely from the rendering process — it takes up zero
space, and surrounding elements shift to fill the gap as if
the element doesn't exist in the layout at all. It's also
removed from the accessibility tree and tab order.visibility: hidden makes
the element invisible but its space is STILL RESERVED in the
layout — surrounding elements don't shift; there's simply an
empty gap where the invisible element would be. It also can't
be transitioned smoothly on its own the way opacity can,
though it CAN be combined with opacity (as is common with
dropdown menus) since visibility, unlike display, supports CSS
transitions.Use
display: none when you
want the element fully gone from layout flow; use
visibility: hidden when
you want to preserve the space it occupies (e.g., hiding one
of several equal-width columns without the others shifting).
Several valid approaches, depending on context:
Flexbox (most common today): on the parent,
Absolute positioning + transform:
Grid: on the parent,
Margin auto (horizontal only): a block element with an explicit
Flexbox (most common today): on the parent,
display: flex; align-items: center; justify-content:
center;
centres any child both horizontally and vertically, regardless
of its size.Absolute positioning + transform:
position: absolute; top: 50%; left: 50%; transform:
translate(-50%, -50%);
— works even when the element's exact size is unknown.Grid: on the parent,
display: grid; place-items: center;
— the shortest one-line solution.Margin auto (horizontal only): a block element with an explicit
width and
margin: 0 auto centres
horizontally only — this technique does NOT work for vertical
centring on its own.
width: 100% sizes the
element to 100% of its PARENT's content width — it naturally
accounts for the parent's own padding and border, never
exceeding what's actually available inside the parent.width: 100vw sizes the
element to 100% of the entire VIEWPORT width — the full
browser window, regardless of what parent it's inside.
Critically, this measurement includes the width of the
vertical scrollbar (when one is present), but the element
itself doesn't know to subtract that scrollbar width from its
own size.This is exactly why 100vw can cause an unwanted horizontal scrollbar: if the page already has a vertical scrollbar taking up, say, 15px, the actual visible content area is 15px narrower than the full viewport — but an element set to
100vw still renders at the
FULL viewport width, overflowing 15px past the visible area
and forcing a horizontal scrollbar to appear.
width: 100% doesn't have
this problem because it's always relative to the actual
available parent width, scrollbar already accounted for.
overflow: hidden clips any
content that extends beyond an element's box boundaries,
rather than letting it spill out visibly or adding scrollbars.
Anything that would render outside the box is simply not
painted.Common practical uses:
— Clipping images into rounded corners: pairing
border-radius with
overflow: hidden on a
container clips a square image into the rounded shape— Clearfix: applying
overflow: hidden to a
parent forces it to expand and contain floated children that
would otherwise escape its height calculation (a legacy
float-layout fix, less needed with flexbox/grid)— Preventing layout breakage: clipping long unbroken text or oversized images that would otherwise overflow and break a card's intended boundaries
— Custom scroll containers: combined with a fixed height, creates a scrollable region for long content within a defined area
width sets a single fixed
or relative target size — the element tries to be exactly that
size regardless of context (though it can still be overridden
by min/max constraints if present).max-width sets an UPPER
LIMIT — the element can be smaller, but never larger than this
value. Extremely common for container elements:
max-width: 1200px; width: 100%;
means the container fills available space up to 1200px, then
stops growing on very wide screens.min-width sets a LOWER
LIMIT — the element can be larger, but never smaller than this
value. Useful for preventing elements (like buttons or form
fields) from becoming uncomfortably small on narrow
screens.Combining
width: 100% with
both min-width and
max-width is one of the
most common responsive patterns — letting an element flex
freely between a sensible floor and ceiling.
3
Flexbox & Grid
Questions 17–24
Flexbox is one-dimensional — it excels at
arranging items along a single axis (a row OR a column) and is
ideal for: navbars, button groups, centring content,
distributing space among an unknown number of items in a line,
or any component where items need to align, wrap, or
grow/shrink relative to each other along one direction.
Grid is two-dimensional — it controls rows AND columns simultaneously, making it ideal for: full page layouts, card grids/galleries, dashboards, or any structure with a defined rows-and-columns relationship where items need to align both horizontally and vertically as a cohesive system.
A common rule of thumb: if you're only thinking about ONE direction at a time, reach for flexbox. If you're thinking about how rows and columns relate to each other together, reach for grid. In practice, the two are frequently combined — a page might use grid for overall layout and flexbox inside individual grid cells.
Grid is two-dimensional — it controls rows AND columns simultaneously, making it ideal for: full page layouts, card grids/galleries, dashboards, or any structure with a defined rows-and-columns relationship where items need to align both horizontally and vertically as a cohesive system.
A common rule of thumb: if you're only thinking about ONE direction at a time, reach for flexbox. If you're thinking about how rows and columns relate to each other together, reach for grid. In practice, the two are frequently combined — a page might use grid for overall layout and flexbox inside individual grid cells.
Both control alignment, but along different axes — and which
axis each one controls depends on
Critically: if you switch to
flex-direction.justify-content aligns
items along the MAIN axis — the primary direction of flow. In
the default
flex-direction: row, the
main axis is horizontal, so justify-content controls
horizontal spacing (start, center, space-between, etc.).align-items aligns items
along the CROSS axis — perpendicular to the main axis. In a
row layout, the cross axis is vertical, so align-items
controls how items line up vertically within the flex
container's height (top, center, bottom, stretch).Critically: if you switch to
flex-direction: column,
the main and cross axes swap — justify-content now controls
VERTICAL spacing and align-items controls HORIZONTAL
alignment. This swap is one of the most common sources of
flexbox confusion.
flex is shorthand for
three values:
flex-grow flex-shrink flex-basis.flex: 1 expands to
flex-grow: 1; flex-shrink: 1; flex-basis: 0%;
— meaning the item starts from zero base size and grows to
fill available space, sharing it proportionally with sibling
items that also have
flex: 1.—
flex-grow: a unitless
number representing how much of the leftover space this item
should claim relative to siblings (a higher number = a bigger
proportional share).—
flex-shrink: how much
this item should shrink relative to siblings when there isn't
enough space — 0 means "never shrink this item below its
basis."—
flex-basis: the item's
starting size before grow/shrink calculations apply — can be a
fixed length (200px) or a percentage.A common pattern
flex: 0 0 200px means
"never grow, never shrink, always exactly 200px" — used for
fixed-width sidebars next to a flexible main content area
(flex: 1).
fr (fractional unit)
represents a share of the AVAILABLE space remaining AFTER all
fixed-size tracks (px, fixed percentages) have been
subtracted.
grid-template-columns: 200px 1fr 2fr
reserves exactly 200px for the first column, then splits
whatever space remains between the second and third columns in
a 1:2 ratio.Percentages are calculated relative to the TOTAL container width, regardless of other tracks' sizes — they don't automatically account for fixed-size siblings the way fr does. Mixing percentages with fixed pixel tracks can cause columns to overflow the container if the percentages plus pixels exceed 100% of the available space.
In practice,
fr units are
almost always preferred over percentages for flexible grid
tracks because they automatically and correctly account for
fixed-size siblings in the same row, something percentages
cannot do reliably.
Breaking this down piece by piece:
As the container shrinks, fewer 200px+ columns fit, so the grid automatically reduces to fewer columns (4 → 3 → 2 → 1), with remaining columns expanding via the
This produces continuously adapting column counts at every pixel of width, rather than the "jump" behaviour of media-query breakpoints (e.g. exactly 1 column below 600px, exactly 2 from 600-900px). It's one of the most powerful, low-code responsive patterns in modern CSS.
minmax(200px, 1fr) defines
a single column track type that's never narrower than 200px,
but can grow up to an equal fractional share (1fr) of any remaining space.
auto-fit tells the grid to
figure out, automatically, how many of these flexible 200px+
columns can fit across the container's current width, and
repeat that pattern exactly that many times.As the container shrinks, fewer 200px+ columns fit, so the grid automatically reduces to fewer columns (4 → 3 → 2 → 1), with remaining columns expanding via the
1fr portion to absorb any
leftover space evenly. As the container grows, more columns
fit and squeeze in.This produces continuously adapting column counts at every pixel of width, rather than the "jump" behaviour of media-query breakpoints (e.g. exactly 1 column below 600px, exactly 2 from 600-900px). It's one of the most powerful, low-code responsive patterns in modern CSS.
Both calculate how many tracks fit in the available space, but
they differ in what happens when there are FEWER actual grid
items than the number of tracks that could fit.
For most card-grid layouts where you want existing cards to fill available width,
auto-fit collapses any
extra, empty tracks down to zero width, allowing the existing
items to STRETCH and fill the remaining space. If a container
could fit 5 columns but only has 3 items, those 3 items expand
to fill the full container width.auto-fill keeps those
extra empty tracks at their full minmax-defined width, even
though no content occupies them — they remain as invisible
placeholder columns. With the same scenario (room for 5, only
3 items), the 3 items stay at their natural minmax width and
the remaining 2 column-widths of empty space sit unused to the
right.For most card-grid layouts where you want existing cards to fill available width,
auto-fit is the more
commonly desired behaviour.
auto-fill is useful when
you specifically want consistent track sizing regardless of
item count (e.g., a calendar grid).
align-self overrides the
parent's align-items value
for one specific flex item, letting it position differently
from its siblings along the cross axis — for example, one card
in a row could be vertically centred while all its siblings
stay top-aligned.There is no equivalent "justify-self" property for flexbox along the main axis (that exists in Grid, not Flexbox) — instead, the common technique to push one flex item away from the rest along the main axis is
margin-left: auto (or
margin-right: auto
depending on direction) on that single item, which consumes
all available leftover space on that side, effectively shoving
it to the opposite end of the row. This is the standard
pattern for, e.g., a navbar where most links are left-aligned
but a "Logout" link needs to sit at the far right.
grid-template-areas lets
you name regions of the grid using a visual, text-based layout
drawn directly in the CSS:grid-template-areas: "header header" "sidebar main" "footer
footer";Each named string literally maps out the grid's shape — repeated words span multiple cells, and each child element is assigned to a named area via
grid-area: header;
etc.The advantage over numeric line-based placement (
grid-column: 1 / 3; grid-row: 2 / 4;) is readability: a developer can glance at the
template-areas declaration and immediately visualise the
entire page structure, whereas numeric line references require
mentally reconstructing the grid to understand what's
happening. For complex page layouts
(header/sidebar/main/footer arrangements), grid-template-areas
is generally considered far more maintainable and
self-documenting, though numeric placement remains useful for
more dynamic or programmatically generated grids.
4
Positioning & Specificity
Questions 25–32
— static (default): normal document flow,
top/left/right/bottom have no effect.
— relative: stays in normal flow but can be nudged using top/left/right/bottom, offset relative to its OWN normal position. Also establishes a positioning context for absolutely positioned descendants.
— absolute: removed from normal flow entirely; positioned relative to the nearest ancestor with position other than static (or the viewport if none exists). Doesn't affect surrounding elements' layout.
— fixed: removed from flow, positioned relative to the VIEWPORT and stays in place even when the page scrolls — used for sticky headers or floating action buttons.
— sticky: hybrid — behaves like relative until the element would scroll past a defined threshold (e.g.
— relative: stays in normal flow but can be nudged using top/left/right/bottom, offset relative to its OWN normal position. Also establishes a positioning context for absolutely positioned descendants.
— absolute: removed from normal flow entirely; positioned relative to the nearest ancestor with position other than static (or the viewport if none exists). Doesn't affect surrounding elements' layout.
— fixed: removed from flow, positioned relative to the VIEWPORT and stays in place even when the page scrolls — used for sticky headers or floating action buttons.
— sticky: hybrid — behaves like relative until the element would scroll past a defined threshold (e.g.
top: 0), then "sticks" in
place like fixed, but only within its containing block's
boundaries.
position: absolute
positions an element relative to its nearest ANCESTOR that has
a position value other than the default
static — meaning relative,
absolute, fixed, or sticky. If NO ancestor in the chain has
one of these positioned values, the browser keeps looking
upward all the way to the document's root, ultimately
positioning the element relative to the entire page (the
initial containing block).This is the single most common cause of "my absolutely positioned element isn't where I expect it" bugs: the developer intends for it to sit relative to its immediate parent, but forgot to add
position: relative to that
parent. The fix is always to add
position: relative (with
no offset values needed — just declaring the property
establishes the positioning context) to the intended anchor
element.
Specificity is calculated as a three-part tuple, often written
(a, b, c):
— a = number of ID selectors
— b = number of class selectors, attribute selectors, and pseudo-classes
— c = number of element/type selectors and pseudo-elements
Comparison happens left to right: any single ID selector (1, 0, 0) beats ANY number of class selectors, because the comparison stops at the first column where the values differ — a single ID always outranks even a hundred chained classes, since the ID column (a) is compared first.
So
— a = number of ID selectors
— b = number of class selectors, attribute selectors, and pseudo-classes
— c = number of element/type selectors and pseudo-elements
Comparison happens left to right: any single ID selector (1, 0, 0) beats ANY number of class selectors, because the comparison stops at the first column where the values differ — a single ID always outranks even a hundred chained classes, since the ID column (a) is compared first.
So
#header (1,0,0) beats
.nav.active.large (0,3,0)
— even though the class selector chain has three components,
it can never out-rank a single ID, because specificity
comparison never "carries over" or sums across columns; it
strictly compares the highest-priority column first.
!important forces a
declaration to override ANY other competing rule regardless of
specificity (with the narrow exception of another `!important`
rule with higher specificity, or a later cascade layer). The
problem is that it breaks the normal, predictable resolution
order of the cascade — once a value is `!important`, the only
way to override it later is with ANOTHER `!important`
declaration with equal or higher specificity, starting an
escalating arms race throughout a codebase that becomes
increasingly difficult to reason about and debug.Better alternatives:
— Increase specificity deliberately and minimally (one extra class, not an ID hack)
— Reorganise source order so the intended rule naturally comes later
— Use CSS cascade layers (
@layer) to control priority explicitly without fighting specificity
at all— Fix the root architectural issue causing the conflict (often an overly specific selector elsewhere that shouldn't exist)
`!important` is occasionally acceptable as a narrow, deliberate escape hatch (e.g., overriding inline styles injected by a third-party widget you don't control), but should never be a routine tool for everyday styling conflicts.
z-index controls the
stacking order of POSITIONED elements along the z-axis (depth)
— higher values render in front of lower values when elements
visually overlap.The most common reason z-index "doesn't work": it only has an effect on elements with a position value other than
static (relative,
absolute, fixed, or sticky). Applying
z-index: 999 to a
statically positioned element does absolutely nothing.The second common gotcha: stacking contexts. Certain CSS properties (like
opacity less than 1,
transform, or explicitly
declaring position with a
z-index) create a NEW stacking context, which isolates z-index
comparisons to within that context only. A child with
z-index: 9999 can never
escape and appear above an element OUTSIDE its parent's
stacking context, no matter how high the number, if that
parent itself has a lower z-index relative to its sibling —
the comparison happens contextually, not globally.
position: fixed is ALWAYS
positioned relative to the viewport, regardless of scroll
position — a fixed header stays pinned to the top of the
screen the entire time the page is open, from the very first
scroll pixel.position: sticky behaves
like relative initially —
it scrolls normally with the page — until the scroll position
reaches a defined threshold (most commonly
top: 0), at which point it
"sticks" in place and behaves like fixed, but ONLY within the
boundaries of its containing block (usually its parent
element). Once the user scrolls past the END of that parent
container, the sticky element scrolls away again along with
it.A common use case for sticky: a section heading that sticks to the top of the viewport WHILE scrolling through that section's content, but then scrolls away normally once you reach the next section — fixed positioning can't replicate this "stick within a bounded region" behaviour, only true viewport-wide pinning.
Both select siblings that come AFTER a reference element
(never before — combinators only look forward in the DOM), but
differ in distance:
Both combinators only work on siblings sharing the same direct parent — they cannot select across different parent containers.
+ (adjacent sibling)
matches only the VERY NEXT sibling immediately following the
reference element —
h2 + p selects a paragraph
only if it's literally the next element right after an h2,
with nothing in between.~ (general/subsequent
sibling) matches ANY sibling that comes after the reference
element, no matter how many other siblings sit in between —
h2 ~ p selects EVERY
paragraph that comes after an h2 within the same parent, not
just the immediately following one.Both combinators only work on siblings sharing the same direct parent — they cannot select across different parent containers.
:not(selector) is a
negation pseudo-class — it matches any element that does NOT
match the selector passed inside its parentheses.
li:not(.active) selects
every list item except those with the "active" class.Yes, it can be chained with itself and other pseudo-classes for compound conditions:
li:not(.active):not(:first-child)
selects list items that are neither active NOR the first child
— both conditions must be satisfied simultaneously, since
chaining multiple `:not()` calls (or any compound selector)
functions as a logical AND.Modern CSS (Selectors Level 4) also allows multiple selectors inside a single `:not()` separated by commas, functioning as a logical OR within that one call:
:not(.active, .disabled)
matches elements that are neither active NOR disabled —
equivalent to but more concise than chaining two separate
`:not()` calls.
5
Modern CSS
Questions 33–40
CSS custom properties are declared with two leading dashes
(
The key advantage over Sass/Less variables: CSS custom properties are LIVE and resolve in the browser at RUNTIME, not at build/compile time. This means JavaScript can read and update them dynamically (
--primary-color: #264de4;) and read with the
var() function (color: var(--primary-color);). They're scoped to whatever element they're declared on
(commonly :root for global
access) and inherit down through descendants like any other
CSS property.The key advantage over Sass/Less variables: CSS custom properties are LIVE and resolve in the browser at RUNTIME, not at build/compile time. This means JavaScript can read and update them dynamically (
element.style.setProperty('--color', 'red')), and a single custom property can have different VALUES at
different points in the DOM simultaneously (e.g., a dark-mode
wrapper redefining
--bg-color for everything
inside it) — something a Sass variable, fixed at compile time
into static values, cannot replicate without separate compiled
CSS classes for each variant.
Before
Common real-world uses: styling a form field wrapper based on whether its input is `:invalid`, styling a card differently if it has no image, and highlighting a parent list item if a checkbox inside it is checked.
:has(), CSS could
select a CHILD based on its parent (.parent .child), but there was no way to select a PARENT based on what it
contains — this required JavaScript to detect the condition
and toggle a class.:has() fixes this:
.card:has(img) selects a
.card element ONLY if it
contains an img somewhere
inside it — the targeted element is the parent, but the
condition examines a descendant. It's nicknamed the "parent
selector" for this reason, though it's more broadly capable,
also supporting sibling combinators to select elements based
on what comes AFTER them in the DOM.Common real-world uses: styling a form field wrapper based on whether its input is `:invalid`, styling a card differently if it has no image, and highlighting a parent list item if a checkbox inside it is checked.
A media query (
A container query (
This distinction matters for reusable components: a card placed in a narrow 250px sidebar and the same card placed in an 800px main content area might both exist at the SAME viewport width simultaneously. A media query can't differentiate between these two placements — it only knows the overall window size. A container query CAN differentiate, because it checks the size of the specific parent the card happens to be inside, letting the exact same component render differently in each context without any extra classes or JavaScript.
@media (min-width: 768px)) responds to the VIEWPORT's size — the browser window
itself.A container query (
@container (min-width: 400px)) responds to the size of a specific PARENT ELEMENT that's
been marked as a query container via
container-type: inline-size.This distinction matters for reusable components: a card placed in a narrow 250px sidebar and the same card placed in an 800px main content area might both exist at the SAME viewport width simultaneously. A media query can't differentiate between these two placements — it only knows the overall window size. A container query CAN differentiate, because it checks the size of the specific parent the card happens to be inside, letting the exact same component render differently in each context without any extra classes or JavaScript.
clamp(MIN, PREFERRED, MAX)
returns a value constrained between a minimum and maximum,
while otherwise following a preferred (typically
viewport-relative) value:font-size: clamp(1rem, 4vw, 2.5rem);— If
4vw evaluates SMALLER
than 1rem (very narrow
viewport), the result is clamped UP to
1rem — never smaller.— If
4vw evaluates LARGER
than 2.5rem (very wide
viewport), the result is clamped DOWN to
2.5rem — never larger.— Anywhere in between, the actual preferred value (
4vw) is used directly, scaling smoothly with the viewport.This produces fluid typography and spacing that scales naturally with screen size but never becomes unreadably small or absurdly large at the extremes — eliminating the need for several separate media-query breakpoints just to adjust font sizes incrementally.
Cascade layers (
This solves the long-standing "specificity wars" problem, where overriding a CSS reset or a third-party framework's moderately specific selectors traditionally required escalating your own selector specificity or reaching for `!important`. By organising styles into named layers by INTENT (reset, base styles, components, utility overrides) rather than relying purely on selector cleverness, developers get predictable, designed-in priority without fighting the cascade.
@layer reset, base, components, utilities;) introduce an explicit priority system that sits ABOVE
specificity in the cascade resolution order. Once layer order
is declared, a rule in a LATER layer always wins over a rule
in an EARLIER layer, no matter how specific the earlier rule's
selector is — a class selector in "utilities" beats an ID
selector in "reset," for example.This solves the long-standing "specificity wars" problem, where overriding a CSS reset or a third-party framework's moderately specific selectors traditionally required escalating your own selector specificity or reaching for `!important`. By organising styles into named layers by INTENT (reset, base styles, components, utility overrides) rather than relying purely on selector cleverness, developers get predictable, designed-in priority without fighting the cascade.
Both describe colours using a Hue/intensity/lightness-style
model, but
In
In
oklch() is
PERCEPTUALLY UNIFORM, while
hsl() is not.In
hsl(), two colours with
the identical lightness value (e.g.
hsl(60, 80%, 50%) yellow
vs
hsl(240, 80%, 50%) blue)
can appear dramatically different in actual PERCEIVED
brightness to the human eye — yellow looks far brighter
despite having the "same" lightness number.In
oklch(), the lightness
channel is calibrated so that equal lightness values produce
equal PERCEIVED brightness across all hues — making it far
more reliable for generating harmonious colour palettes or
scales where every step should look consistently bright or
dark. oklch() also
accesses wider-gamut P3 display colours that
hsl() (restricted to sRGB)
cannot reach, which is why modern design systems are
increasingly adopting it as their primary colour space.
Native CSS nesting (supported in all major browsers since
2023) lets you write a child selector directly inside a parent
selector's curly braces, without a preprocessor like Sass:
The
Important: nesting is purely a writing convenience and does NOT change specificity — a nested rule has identical specificity to the equivalent rule written out flat.
.card { .title { color: red; } }
compiles, conceptually, to
.card .title { color: red; }.The
& symbol
explicitly represents the parent selector and is REQUIRED
whenever the nested rule attaches directly without whitespace
— pseudo-classes (&:hover), compound classes (&.active), or pseudo-elements (&::before). Without &, the browser would interpret
:hover { } as an
unrelated, separate top-level rule rather than as a state of
the parent. For plain descendant selectors with implicit
whitespace separation (like the
.title example above),
& is optional.Important: nesting is purely a writing convenience and does NOT change specificity — a nested rule has identical specificity to the equivalent rule written out flat.
Scroll snap is a pair of CSS properties that let the browser
handle "snapping" scroll position to fixed points natively,
without any JavaScript carousel library.
Combined with
scroll-snap-type goes on
the SCROLL CONTAINER (the parent with
overflow-x: auto) and
enables snapping on a given axis with a strictness level:
scroll-snap-type: x mandatory;
means the container always snaps along the horizontal axis
once scrolling stops.scroll-snap-align goes on
each CHILD ITEM and defines where it should align when snapped
— typically start for a
carousel where each slide should align to the left edge of the
visible area.Combined with
display: flex; overflow-x: auto;
on the container and a fixed or flexible width on each child
slide, this produces a fully swipeable, touch-friendly,
accessible carousel using only CSS. JavaScript is only needed
for OPTIONAL extras like navigation dot indicators, arrow
buttons, or autoplay — never for the core scrolling and
snapping mechanics themselves.
120+
Chapters
40 hrs
Content
10 Real
Projects
4.9 ⭐
Rating
HTML5CSS3JavaScriptReact.jsNode.jsTailwind CSSAI Tools
- Group 1 — Fundamentals: how CSS is applied, the cascade, selectors, units, display types, pseudo-classes vs pseudo-elements.
- Group 2 — Box Model & Layout: box-sizing, margin collapse, display vs visibility, centring techniques, viewport units, overflow.
- Group 3 — Flexbox & Grid: when to use which, justify-content vs align-items, the flex shorthand, fr units, auto-fit/auto-fill, grid-template-areas.
- Group 4 — Positioning & Specificity: the five position values, positioning contexts, specificity calculation, !important, z-index and stacking contexts, combinators, :not().
- Group 5 — Modern CSS: custom properties, :has(), container queries, clamp(), cascade layers, oklch(), native nesting, scroll-snap.
- Interview tip: don't just memorise definitions — practice explaining the REASONING behind each answer (the "why"), since most interviewers probe follow-up questions to test genuine understanding rather than rote recall.
Rate Us on Google
Enjoying this tutorial?
Your 5-star review helps other learners discover our free
tutorials and encourages us to keep creating quality content.
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.