CSS Interview Questions & Answers
Curated CSS interview questions with detailed answers, grouped by topic. Search, revise and get interview-ready.
CSS Introduction
Cascading Style Sheets. It styles HTML — controlling colors, fonts, spacing, layout, and animation — without changing the underlying content or structure.
A selector, which determines which elements are targeted, and a declaration block, which contains the property/value pairs to apply to them.
It describes how CSS resolves conflicts when multiple rules target the same element — based on source order, specificity, and importance — rather than the last rule always simply overwriting the others.
CSS Setup
Inline (a style attribute on an element), internal (a <style> block in the document), and external (a linked .css file).
They are cached by the browser, keep styles consistent across many pages, and cleanly separate content (HTML) from presentation (CSS).
They mix content with presentation, are hard to override due to high specificity, and can’t be reused across elements or cached separately from the HTML.
CSS Syntax
A colon separates property and value (e.g. color: red), and a semicolon ends each declaration.
The next declaration gets merged into the value of the previous one, silently breaking both — always terminate every declaration with a semicolon.
Between /* and */. Comments can span multiple lines and are ignored entirely by the browser.
CSS Selectors
A class selector (.name) can match many elements and is reusable; an ID selector (#name) should match only one unique element per page and carries much higher specificity.
Every element that has a matching attribute and value — useful for styling form inputs by type without adding extra classes.
By grouping them with commas, e.g. h1, h2, h3 { color: #222; }, avoiding repeated declaration blocks.
CSS Colors
Named colors (tomato), hex (#ff6347), rgb()/rgba(), and hsl()/hsla() — all interchangeable wherever a color value is expected.
Transparency, from 0 (fully transparent) to 1 (fully opaque), letting you layer a semi-transparent color over other content.
HSL describes color the way humans think about it — hue, saturation, lightness — making it far easier to create consistent variations, like a slightly darker hover state, than guessing new hex values.
Units & Values
em is relative to the current element’s own font size (and compounds with nesting), while rem is always relative to the root <html> element’s font size, making it more predictable.
1vw is 1% of the viewport width and 1vh is 1% of the viewport height, useful for elements that should scale with the browser window.
rem scales with the user’s root font size setting, which matters for accessibility — users who increase their browser’s default font size for readability will see rem-based text scale accordingly, unlike fixed px values.
The Box Model
From innermost to outermost: content, padding, border, and margin.
Yes — with the default content-box sizing, width only refers to the content area, so padding and border are added on top of it, increasing the total rendered size.
It makes the specified width/height include padding and border, so the element’s total rendered size matches the value you set — a very common global reset.
Text & Fonts
If none of the listed fonts are available on the user’s system, the browser falls back to the generic family (like sans-serif), ensuring text always renders reasonably instead of using an unpredictable default.
The boldness of text, typically from 100 (thin) to 900 (black), with 400 being normal and 700 being bold.
Roughly 1.4 to 1.6 (a unitless value, so it scales with the element’s own font size) — tighter values feel cramped, and much looser values feel disconnected.
CSS Backgrounds
cover scales the image to fully cover the box, cropping if necessary. contain scales it to fit entirely within the box, potentially leaving empty space.
It gives a reasonable appearance while the image is loading or if it fails to load entirely, especially important for text readability over what would otherwise be an empty background.
With background-repeat: no-repeat.
Borders & Border Radius
Width, style, and color, in that order — e.g. border: 2px solid black.
50%, applied to an element with equal width and height.
Using a directional property like border-left, border-top, border-right, or border-bottom, each accepting the same width/style/color shorthand.
Margin & Padding
padding adds space inside an element, between its content and its border. margin adds space outside an element, separating it from its neighbors.
It centers the element horizontally within its parent, by splitting the remaining horizontal space equally between the left and right margins.
When adjacent vertical margins between block elements combine into a single margin equal to the larger of the two, rather than adding together. It only happens with vertical margins, never horizontal ones.
The display Property
display: none removes the element entirely — it takes up no space. visibility: hidden hides it visually but still reserves its layout space.
It lets the element accept width and height like a block element, while still flowing inline alongside surrounding content.
It turns them into flex items, enabling properties like justify-content, align-items, and flex to control their alignment and sizing along a row or column.
CSS Positioning
static — the element follows normal document flow, and top/right/bottom/left have no effect on it.
Its nearest ancestor with a position value other than static. If no such ancestor exists, it’s positioned relative to the entire page.
It behaves like relative until the page scrolls past a defined threshold (e.g. top: 0), then it behaves like fixed within its containing block.
fixed is always positioned relative to the viewport and stays in place while scrolling. absolute is positioned relative to the nearest positioned ancestor and scrolls with the page.
Flexbox
It turns an element into a flex container, making its direct children flex items that can be aligned and distributed along a row or column using Flexbox properties.
justify-content aligns items along the main axis (e.g. horizontally in a row), while align-items aligns them along the cross axis (e.g. vertically in a row).
It allows the item to grow and shrink to fill the available space in the container, sharing that space proportionally with any other flexible siblings.
By setting display: flex, justify-content: center, and align-items: center on the container.
CSS Grid
Grid is a two-dimensional layout system, controlling rows and columns together. Flexbox is one-dimensional, aligning items along a single row or column.
A fraction of the available space in the grid container — grid-template-columns: 1fr 2fr creates two columns, the second twice as wide as the first.
It lets you visually sketch a layout using named regions directly in your CSS, then assign each child element to a named area with grid-area.
Overflow & Visibility
hidden clips extra content with no scrollbar at all. auto shows a scrollbar only when the content actually overflows its container.
By combining white-space: nowrap, overflow: hidden, and text-overflow: ellipsis on the element.
They control overflow behavior independently per axis — overflow-x for horizontal, overflow-y for vertical — useful for a horizontally scrolling carousel with hidden vertical overflow.
z-index & Stacking
No — z-index only has an effect on positioned elements (relative, absolute, fixed, or sticky).
A stacking context groups elements so z-index comparisons happen within it, not globally. Besides position + z-index, properties like opacity less than 1, transform, and filter can also create a new stacking context.
If its parent is in a separate stacking context with a lower z-index than a competing element, the child can never escape that stacking context to appear above it, regardless of its own z-index value.
Pseudo-classes
It targets an element in a particular state or position without needing extra markup, written with a single colon, e.g. :hover or :nth-child(2).
Keyboard and screen-reader users rely on visible focus indicators to know where they are on the page — :hover alone provides no feedback for non-mouse interaction.
Using li:nth-child(odd) or li:nth-child(even), which targets alternating children without needing extra classes.
Pseudo-elements
Pseudo-elements use a double colon (::before) and target a specific part of an element or insert generated content, while pseudo-classes (single colon) target an existing element in a certain state.
The content property — even content: "" (empty string) is valid and commonly used just to insert a styled shape.
Generated content isn’t part of the real DOM and may not be reliably read by all assistive technology, so it should be reserved for purely decorative purposes.
Specificity & the Cascade
An ID selector — IDs outweigh any number of class, attribute, or pseudo-class selectors combined, but are themselves outweighed by inline styles.
The one that appears later in the stylesheet — this is the "cascading" part of Cascading Style Sheets.
It overrides normal specificity almost entirely, making styles unpredictable and hard to override later — often forcing even more !important rules to work around it.
Combinators
The descendant combinator (a space, e.g. "div p") matches any matching element nested at any depth. The child combinator (>, e.g. "div > p") matches only direct children.
The single element that comes immediately after another, sharing the same parent — e.g. h2 + p selects only the paragraph directly following an h2.
When you specifically mean "direct children only" — it keeps styles from unintentionally leaking into deeply nested, unrelated elements as markup grows.
Responsive Design
A block of CSS that only applies when certain conditions are met, most commonly viewport width, e.g. @media (max-width: 480px) { ... }.
Writing base styles for small screens first, then progressively adding complexity for larger screens using min-width media queries, rather than starting from desktop and overriding down.
Without <meta name="viewport" content="width=device-width, initial-scale=1.0" />, mobile browsers render the page at a zoomed-out desktop width, which breaks the intent of media queries.
CSS Variables
Define it with two leading dashes, typically on :root, e.g. --brand-color: #764ba2;, and reference it anywhere with var(--brand-color).
CSS variables are live in the browser at runtime — they can be read and updated dynamically (even via JavaScript), unlike preprocessor variables which are compiled away and fixed at build time.
By passing a second argument to var(), e.g. var(--spacing, 10px), which is used if --spacing is not defined.
Transitions
It smooths out a property change over a duration instead of it happening instantly, commonly combined with a state change like :hover.
Property, duration, timing-function, and delay — e.g. transition: transform 0.4s ease-in-out 0.1s.
They can be animated efficiently by the browser’s compositor without triggering expensive layout recalculations, unlike properties like width, height, or top.
Animations
A transition animates between exactly two states, usually triggered by an event. An animation, defined with @keyframes, can have multiple steps and run automatically or repeat without any trigger.
It makes the animation loop indefinitely instead of stopping after a fixed number of cycles.
Some users experience discomfort from motion due to vestibular disorders. Wrapping animations in @media (prefers-reduced-motion: no-preference) respects the OS-level accessibility setting some users enable.
Transforms
No — transform is purely visual and does not reflow surrounding content, unlike changing width, margin, or position offsets.
The pivot point that transforms like rotate() and scale() are calculated from — by default the center of the element.
In the order they are written — e.g. transform: translateX(20px) rotate(10deg) first translates the element, then rotates it around its (already translated) origin.
Shadows & Filters
It makes the shadow appear inside the element’s box instead of outside, creating a "pressed in" appearance.
box-shadow adds a shadow around an element’s entire box, while text-shadow applies specifically to the glyphs of text.
Graphical effects like blur(), brightness(), grayscale(), and contrast(), often used for image effects or interactive hover states.
Gradients
linear-gradient() transitions colors along a straight line at a given angle, while radial-gradient() radiates outward from a center point.
Through background-image (or the background shorthand) — gradients are treated as images in CSS, not colors.
It sweeps colors around a center point like a color wheel or pie chart, rather than radiating outward or moving along a line.
CSS Functions
It performs math directly in a value and can mix different units, e.g. calc(100% - 150px), which isn’t possible with a plain arithmetic value.
It picks a value that scales with the preferred expression but never goes below min or above max — commonly used for fluid typography that scales with the viewport within safe bounds.
min() resolves to the smallest of a list of values, and max() resolves to the largest — both evaluated live, so they respond to viewport or container size changes.
CSS Best Practices
Block, Element, Modifier — a naming convention (.block__element--modifier) that keeps class names descriptive and flat, avoiding deep selector nesting and specificity conflicts.
It makes width/height calculations include padding and border, so an element’s specified size matches its actual rendered size, avoiding a very common layout surprise.
Any convention applied unpredictably becomes as confusing as no convention at all. Consistently applying one system lets any developer predict what a class does without hunting through the whole stylesheet.