Table of Contents
CSS interviews have changed. Interviewers still ask about the box model, specificity and positioning, but they now also expect you to know flexbox, grid, custom properties and newer features such as container queries and :has(). This guide gives you 50 questions with short, correct answers and code you can run, grouped into basic, intermediate and advanced levels, plus five scenario questions and a quick quiz.
If you are a fresher, start with the basic questions and the cheat sheet at the end. If you have a year or more of experience, spend most of your time on the intermediate and advanced sections, because those are where interviews are won or lost. Every answer is written the way you would say it out loud: the definition first, then one example.
How to use this guide
- Read the question and answer it aloud before you read the answer.
- Type the code examples into a browser and change them; interviewers often ask “what happens if…”.
- Finish with the scenario questions, which mirror live-coding rounds.
Basic CSS interview questions (1 to 15)
1. What is CSS and why is it used?
CSS (Cascading Style Sheets) is the language that controls how HTML looks: colours, fonts, spacing and layout. It separates content (HTML) from presentation, so one stylesheet can style many pages and a redesign does not mean editing every page.
2. What are the three ways to add CSS to a page?
- Inline: the
styleattribute on one element, for example<p style="color: red;">. Hard to reuse and hard to override. - Internal: a
<style>block in the page’s<head>. Fine for one-off pages. - External: a separate
.cssfile linked with<link rel="stylesheet" href="styles.css">. This is the standard choice because the browser caches the file and every page shares it.
3. What is a CSS selector? Name the common types.
A selector tells the browser which elements a rule applies to. The common types are type (p), class (.card), ID (#hero), attribute ([type="text"]), universal (*) and combinators: descendant (div p), child (div > p), adjacent sibling (h2 + p) and general sibling (h2 ~ p).
4. What is the difference between a class and an ID selector?
An ID (#header) must be unique in a page, while a class (.btn) can be reused on any number of elements, and an element can have several classes. An ID selector is also more specific, so it wins conflicts. In practice, style with classes and keep IDs for fragment links and JavaScript hooks.
5. How do you apply the same style to several elements?
Group the selectors with commas:
h2, h3 {
color: blue;
}
6. What is the CSS box model?
Every element is a rectangular box made of four layers, from inside out: content, padding, border and margin. Width and height set the content box by default, so padding and border are added on top of them (see question 18 for box-sizing).
7. What is the difference between margin and padding?
Padding is the space inside the border, between the content and the border, and it takes the element’s background. Margin is the space outside the border, between this element and its neighbours, and it is always transparent. Vertical margins of adjacent block elements can collapse into one.
8. What is the difference between block, inline and inline-block?
block: starts on a new line and fills the available width; width, height, margin and padding all apply (div,p).inline: flows within a line of text; width and height are ignored and vertical margins have no effect (span,a).inline-block: flows like inline but accepts width and height.
9. How do you set colours in CSS, and what is the RGB range?
You can use a named colour (red), hex (#ff0000), rgb() or hsl(). In RGB each channel runs from 0 to 255, so rgb(255 0 0) is pure red. To change a background colour:
.hero {
background-color: #1e90ff;
}
10. Which units does CSS use, and how do em and rem differ?
px is fixed. % is relative to the parent. vw and vh are relative to the viewport. em is relative to the element’s own font size (for font-size itself, the parent’s), so nested em values compound. rem is relative to the root (html) font size, which makes it predictable. Use rem for font sizes and spacing.
11. What does “cascading” mean?
When several rules target the same property on the same element, the browser picks the winner in this order: origin and !important, then specificity, then source order (the later rule wins on a tie). Cascade layers, covered in question 33, add one more step.
12. What does !important do, and should you use it?
It makes a declaration beat normal declarations regardless of specificity. Use it sparingly, for example to override a third-party stylesheet you cannot edit. Routinely reaching for it is a sign the selectors need restructuring, because the only way to beat it is another !important.
13. What is a pseudo-class?
A pseudo-class selects an element based on its state or position, written with one colon: a:hover, input:focus, li:first-child, li:nth-child(2n). Pseudo-elements, such as ::before, are covered in question 19.
14. What is the difference between CSS2 and CSS3?
CSS3 is not one release. After CSS2.1 the language was split into independent modules, each versioned separately (Selectors, Flexbox, Grid, Media Queries and so on). Features people usually credit to “CSS3” are rounded corners, shadows, gradients, transitions, animations, media queries, flexbox and grid.
15. What is a CSS framework? Name a few.
A framework is a prebuilt set of styles and layout tools. Bootstrap ships ready-made components, Tailwind CSS is utility-first (you compose small classes such as p-4 and flex), and Bulma is a lightweight alternative. Frameworks speed up delivery but add size and can hide how CSS works, so interviewers still test the fundamentals.
Intermediate CSS interview questions (16 to 30)
1: Which of the following is a JavaScript framework/library?
16. How does CSS specificity work?
When two rules conflict, the more specific selector wins. Think of it as three counters, compared left to right: IDs, then classes, attributes and pseudo-classes, then element types and pseudo-elements. Inline styles beat all of them, and the universal selector and combinators add nothing.
a { } /* 0,0,1 */
.nav a { } /* 0,1,1 */
#header .nav a { } /* 1,1,1 wins over both */
If specificity ties, the rule that appears later wins. :where() adds zero specificity, and :is() takes the specificity of its most specific argument.
17. What is inheritance in CSS?
Some properties pass from a parent to its children automatically, mainly text-related ones: color, font-family, line-height, text-align, visibility. Box properties such as margin, padding, border, background and width do not inherit. You can control this with the keywords inherit, initial, unset and revert.
18. What does box-sizing do?
With the default content-box, width and height set the content only, so a width: 200px box with 20px padding and a 5px border is 250px wide. With border-box, width includes padding and border, so the same box stays 200px wide. Most projects set it globally:
*, *::before, *::after {
box-sizing: border-box;
}
19. What is the difference between pseudo-classes and pseudo-elements?
A pseudo-class (one colon) selects an existing element in a particular state, such as :hover, :focus-visible or :nth-child(2). A pseudo-element (two colons) styles a part of an element or generates content, such as ::before, ::after, ::first-line and ::placeholder. ::before and ::after only render if you set content:
.required::after {
content: " *";
color: crimson;
}
20. Explain the position values.
static: the default; normal flow, offsets ignored.relative: stays in flow and is offset from its normal position; it also becomes the reference point for absolute children.absolute: removed from flow and placed relative to its nearest positioned ancestor (or the page if there is none).fixed: placed relative to the viewport and stays put when you scroll.sticky: behaves likerelativeuntil it reaches a scroll threshold such astop: 0, then sticks within its parent. It needs an offset to work, and it fails if an ancestor hasoverflowset to something other thanvisible.
21. How does z-index work, and what is a stacking context?
z-index sets the stacking order of positioned elements (and flex or grid items). The default is auto, and a higher value is drawn on top, but only within the same stacking context. A new stacking context is created by the root element, by position plus a z-index value, and by properties such as opacity below 1, transform, filter and isolation: isolate. A child can never escape its parent’s context, which is why z-index: 9999 sometimes still loses.
22. What is the difference between display: none, visibility: hidden and opacity: 0?
display: none: removed from layout and from the accessibility tree; takes no space.visibility: hidden: invisible but still takes up space; not clickable and not read by screen readers.opacity: 0: invisible but still takes up space, and it can still be clicked and focused, so use it with care.
23. What is float, and is it still used?
float pushes an element left or right so text wraps around it, which is still the right tool for wrapping text around an image. It was once used for whole-page layouts, which needed clear or a clearfix hack to stop the parent collapsing. Today layout is done with flexbox and grid, and display: flow-root on the parent contains floats without a hack.
24. How do you centre an element horizontally and vertically?
The shortest modern ways are flexbox or grid on the parent:
.parent {
display: grid;
place-items: center;
}
/* or */
.parent {
display: flex;
justify-content: center;
align-items: center;
}
For horizontal-only centring, use text-align: center for inline content or margin-inline: auto on a block with a set width.
25. What is flexbox and how does it work?
Flexbox lays out items in one dimension, along a row or a column. On the container, flex-direction sets the main axis, justify-content distributes items along it, align-items aligns them on the cross axis, gap sets spacing and flex-wrap lets items wrap. On items, flex: 1 is shorthand for flex: 1 1 0% (grow, shrink, basis), so items share the free space equally.
26. What is CSS grid, and when do you choose it over flexbox?
Grid lays out in two dimensions, rows and columns at once:
.cards {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
gap: 1rem;
}
Choose grid when you are designing the page or component layout first and placing content into it; choose flexbox when the content’s size should drive a single row or column, such as a navbar or a button group. They are often combined.
27. What are media queries, and what does mobile-first mean?
Media queries apply styles only when a condition is true, such as viewport width. Mobile-first means writing the base styles for small screens and adding min-width queries for larger ones:
.container { padding: 1rem; }
@media (min-width: 768px) {
.container { padding: 2rem; }
}
They also detect user preferences, for example prefers-color-scheme and prefers-reduced-motion. Remember the <meta name="viewport" content="width=device-width, initial-scale=1"> tag in the HTML.
28. What are CSS custom properties (variables)?
Custom properties are values you define with a -- prefix and read with var(). Unlike Sass variables, they exist at runtime, follow the cascade and inheritance, can be changed per element or with JavaScript, and make theming simple:
:root { --brand: #0a66c2; }
.btn { background: var(--brand, #333); }
29. How do transitions differ from animations?
A transition animates a property from one state to another when something triggers it, such as :hover, using transition: opacity 0.3s ease. An animation uses @keyframes to define multiple steps, can run automatically, repeat and alternate, and does not need a trigger. For smooth performance, animate transform and opacity, which the browser can handle without recalculating layout.
30. What is the difference between a CSS reset and normalize.css?
A reset removes nearly all default browser styling (margins, list styles, font sizes) so you start from zero. Normalize.css keeps useful defaults and only fixes inconsistencies between browsers. Many teams now use a small modern reset instead: box-sizing: border-box, zero margins, and img { max-width: 100%; display: block; }.
🚀 Start Coding Today! Enroll Now with Easy EMI Options. 💳✨
Get Hired as a Full-Stack Developer: Master the Skills Employers Are Looking For!
Start Learning With EMI Payment OptionsAdvanced and modern CSS interview questions (31 to 45)
31. What are container queries?
Container queries apply styles based on the size of a parent container instead of the viewport, so a component adapts to wherever it is placed. Mark the parent as a container, then query it:
.sidebar { container-type: inline-size; }
@container (min-width: 32rem) {
.card { grid-template-columns: 1fr 2fr; }
}
Support arrived in Chrome 105, Safari 16 and Firefox 110. The answer interviewers want: media queries ask “how big is the screen?”, container queries ask “how much room does this component have?”.
32. What does the :has() selector do?
:has() is the long-awaited parent selector: it matches an element based on what it contains or what follows it.
.field:has(input:invalid) { border-color: crimson; }
.card:has(img) { padding-top: 0; }
It shipped in Safari 15.4 and Chrome 105, and Firefox added it in version 121 (December 2023). So the old claim that CSS cannot select a parent no longer holds.
33. What are cascade layers (@layer)?
Layers let you declare an explicit order between groups of styles. A rule in a later layer beats a rule in an earlier layer regardless of specificity, and unlayered styles beat layered ones.
@layer reset, base, components, utilities;
@layer utilities {
.p-0 { padding: 0; }
}
This solves specificity wars with third-party CSS: put the library in an early layer and your own styles win without !important. For !important declarations the order reverses, so earlier layers win. Support: Chrome 99, Firefox 97, Safari 15.4.
34. What is native CSS nesting?
You can nest rules inside their parent without a preprocessor, and & refers to the parent selector:
.card {
padding: 1rem;
&:hover { border-color: #000; }
h2 { margin: 0 0 0.5rem; }
}
Current syntax is supported from Chrome 120, Firefox 117 and Safari 17.2.
35. What is the difference between :is() and :where()?
Both match any selector in a list, which shortens long selectors: :is(h1, h2, h3) a. The difference is specificity: :is() takes the specificity of its most specific argument, while :where() always contributes zero. Use :where() for defaults in a reset or library that others should be able to override easily.
36. What is subgrid?
Subgrid lets a nested grid use its parent’s rows or columns, so items inside sibling cards line up with each other:
.card {
display: grid;
grid-row: span 3;
grid-template-rows: subgrid;
}
It is supported in Firefox 71, Safari 16 and Chrome 117.
37. How do clamp(), min() and max() help with responsive design?
clamp(min, preferred, max) keeps a value between two limits while it scales in between, which gives fluid typography without media queries:
h1 { font-size: clamp(1.75rem, 1rem + 3vw, 3rem); }
Include a rem part in the preferred value, as above, so text still responds to the user’s browser font-size setting.
38. What are logical properties?
Logical properties describe sides by writing direction instead of physical edges: margin-inline, padding-block, border-inline-start, inset-inline-end. In a right-to-left language such as Arabic, the layout mirrors automatically, so you do not need separate overrides.
39. What are aspect-ratio and the dvh, svh and lvh units for?
aspect-ratio: 16 / 9 keeps a box’s proportions without the old padding-top hack. On mobile browsers, 100vh includes the area behind the collapsing address bar, which causes jumpy layouts. svh is the viewport with the browser bars showing, lvh with them hidden, and dvh follows the current state, so min-height: 100dvh or 100svh is the reliable full-screen height.
40. How do you animate efficiently, and what is will-change?
Changing width, top or margin forces the browser to recalculate layout, which is expensive. Animating transform and opacity can usually be handled by the compositor without layout or repaint, so prefer them. will-change: transform hints that an element is about to change so the browser can prepare, but each hint costs memory, so apply it only to elements that are actually about to animate and remove it afterwards.
41. How would you improve CSS performance?
- Remember that stylesheets in the
<head>block rendering, so keep them small: minify, remove unused rules, and inline only the critical CSS for the first screen. - Use
content-visibility: autoon long off-screen sections so the browser skips rendering them until needed. - Avoid layout thrashing in animations (see question 40).
- Keep selectors simple and short; they are rarely the bottleneck, but deep nesting makes CSS harder to override and maintain.
42. How do you structure CSS in a large project?
Common approaches are BEM naming (.card__title--active), utility-first CSS such as Tailwind, component-scoped styles (CSS Modules or CSS-in-JS in a framework) and cascade layers to order base, component and utility styles. The best answer names the trade-off: BEM is explicit but verbose, utilities are fast but crowd the markup, and scoped styles prevent leaks but need tooling.
43. Do you still need Sass or Less?
Less than before. Native CSS now has custom properties, nesting, calc(), clamp() and color-mix(). Sass still offers mixins, functions, loops and partial imports that CSS lacks, so it remains common in existing codebases. A fair answer: use native features by default and add a preprocessor when you need its logic features.
44. How do you write accessible CSS?
- Never remove
outlinewithout a visible replacement; use:focus-visiblefor keyboard focus styling. - Respect motion preferences:
@media (prefers-reduced-motion: reduce) { * { animation: none; } }. - Keep text contrast at or above 4.5:1 for normal text (WCAG AA), and never rely on colour alone to convey meaning.
- Size text in
remso it scales with the user’s settings. - Remember
display: noneandvisibility: hiddenhide content from screen readers too.
45. How do you implement dark mode?
Define colours as custom properties and swap them under prefers-color-scheme:
:root {
color-scheme: light dark;
--bg: #fff;
--text: #111;
}
@media (prefers-color-scheme: dark) {
:root { --bg: #111; --text: #eee; }
}
body { background: var(--bg); color: var(--text); }
To let users toggle it, override the same variables under a [data-theme="dark"] attribute on <html>.
Scenario and live-coding questions (46 to 50)
These mirror what interviewers ask in machine-coding rounds. Say your approach aloud before you type.
46. Build a responsive card grid without a single media query.
.cards {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(min(240px, 100%), 1fr));
gap: 1rem;
}
Each column is at least 240px and shares leftover space equally. auto-fit collapses empty tracks so the cards stretch to fill the row, while auto-fill would keep empty tracks. The min(240px, 100%) stops a card overflowing on very narrow screens.
47. Make a header that stays at the top while the page scrolls.
.site-header {
position: sticky;
top: 0;
z-index: 10;
background: #fff;
}
If it does not stick, check three things: an offset such as top: 0 is set, no ancestor has overflow other than visible, and the header has a background and z-index so content does not show through or cover it.
48. A CSS rule is not being applied. How do you debug it?
- Open DevTools and select the element: a struck-through declaration was overridden, and a warning icon means the value is invalid.
- Check the selector for typos and compare specificity with the rule that won.
- Check source order and whether the stylesheet actually loaded (Network tab, hard refresh for caching).
- Check whether the property inherits, and whether the element’s
displayallows it, for examplewidthon an inline element. - Check media queries,
@layerorder and any!importantelsewhere.
49. Centre a modal over the page with a dimmed background.
.overlay {
position: fixed;
inset: 0;
display: grid;
place-items: center;
background: rgb(0 0 0 / 0.5);
}
Add overflow: hidden to body while it is open to stop the page scrolling behind it. A better answer mentions the native <dialog> element: calling showModal() puts it in the top layer, gives you a ::backdrop to style, closes on Esc and makes the rest of the page inert, which covers most of the accessibility work for you.
50. Truncate text with an ellipsis, on one line and on three lines.
/* one line */
.title {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
/* three lines */
.excerpt {
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 3;
overflow: hidden;
}
A standard line-clamp property is on its way, but check browser support before relying on it; the -webkit- version above works across current browsers.
Quick quiz (answers at the end)
- What is the default value of
z-index?- a)
0 - b)
1 - c)
auto - d)
-1
- a)
- A box has
width: 200px,padding: 20pxandborder: 5pxwith the defaultbox-sizing. How wide is it on screen?- a) 200px
- b) 225px
- c) 250px
- d) 245px
- Which selector has the highest specificity?
- a)
div.card - b)
.card.active - c)
#card - d)
div p span
- a)
- Which declaration on a grid container centres its children in both directions?
- a)
text-align: center - b)
place-items: center - c)
vertical-align: middle - d)
float: center
- a)
- What does
:has()let you do?- a) Select an element based on what it contains
- b) Select the first child only
- c) Add generated content
- d) Set a fallback value for a variable
- Which of these hides an element but keeps its space and still lets it be clicked?
- a)
display: none - b)
visibility: hidden - c)
opacity: 0 - d)
position: static
- a)
Answer key: 1-c, 2-c (200 + 2 × 20 + 2 × 5 = 250), 3-c (an ID beats any number of classes), 4-b, 5-a, 6-c.
🚀 Start Coding Today! Enroll Now with Easy EMI Options. 💳✨
Get Hired as a Full-Stack Developer: Master the Skills Employers Are Looking For!
Start Learning With EMI Payment OptionsOne-page CSS cheat sheet
| Topic | Remember |
|---|---|
| Specificity | Inline, then ID, then class/attribute/pseudo-class, then element/pseudo-element; ties go to the later rule |
| Box model | Content, padding, border, margin; set box-sizing: border-box |
| Position | static, relative, absolute, fixed, sticky |
| Centre anything | display: grid; place-items: center |
| Layout | Flexbox for one axis, grid for two |
| Responsive | Mobile-first min-width queries, clamp(), container queries |
| Units | rem for type and spacing, % and fr for layout, dvh for full-screen height |
| Modern selectors | :has(), :is(), :where(), nesting with & |
| Ordering styles | @layer beats specificity between layers |
| Performance | Animate transform and opacity; keep critical CSS small |
| Accessibility | :focus-visible, prefers-reduced-motion, 4.5:1 text contrast |
FAQs
How many CSS interview questions should I prepare? Freshers should be comfortable with the 15 basic questions and most of the intermediate ones. For 2 to 5 years of experience, add the advanced section and practise two or three live-coding tasks from the scenario section.
Which CSS topics matter most for freshers? The box model, selectors and specificity, positioning, flexbox, grid, responsive design with media queries, and units. These cover most first-round questions.
Are flexbox and grid asked in interviews? Yes, almost always. Expect “flexbox vs grid”, centring an element, and building a responsive card layout.
Do interviewers ask about newer features like :has(), container queries and @layer? Increasingly, for mid-level and senior roles. Know what each does, one practical use, and the browser support position.
What is the best way to prepare? Build small layouts from scratch without a framework, explain each declaration aloud, and debug broken CSS in the browser DevTools. Interviewers care more about reasoning than memorised definitions.
Should I learn Sass or Tailwind for interviews? Only if the job description lists them. Native CSS now covers variables, nesting and layers, so strong fundamentals matter more.
Conclusion
CSS interviews test whether you understand how the browser lays out and styles a page, not whether you can recite property names. Work through the questions above, write the code yourself, and be ready to explain why a solution works. Pair that with real projects and you will be prepared for most front-end rounds.
Experience the power of our full stack development course with a free demo – enroll now!




