62 questions - Beginner to intermediate

CSS interview questions and answers

CSS interviews are mostly about three things: how the box model works, how the browser decides which rule wins, and how you build a layout that survives on a small screen. Learn those well and the rest is detail.

CSS fundamentals

Selectors, the cascade and how rules are chosen.

What is CSS?

CSS means Cascading Style Sheets. HTML says what the content is, CSS says how it should look - colour, size, spacing and position. "Cascading" means several rules can apply to the same element, and CSS has a set order to decide which one wins.

What are the three ways to add CSS to a page?

Inline with a style attribute on the element, internal inside a <style> tag in the head, and external in a .css file linked with <link>. External is best because one file styles the whole site and the browser can cache it.

What is the cascade?

It is the order the browser uses to pick a winner when several rules target the same element. It checks origin and importance first, then specificity, and finally source order - the rule written last wins if everything else is equal.

What is specificity and how is it calculated?

Specificity is a score for how precise a selector is. Count inline styles as 1000, each id as 100, each class, attribute or pseudo-class as 10, and each element or pseudo-element as 1. The higher score wins. A tie is broken by whichever rule comes later in the file.

/* 0,0,1,1 = 11  */  div.card { }
/* 0,1,0,0 = 100 */  #hero { }        /* this one wins */
/* 0,0,2,0 = 20  */  .card.active { }

What does !important do and why avoid it?

It forces a declaration to beat normal specificity. Avoid it because the next person then needs another !important to override it, and very soon nobody can predict which style applies. Fix the specificity instead.

What is inheritance in CSS?

Some properties pass down from a parent to its children automatically - mostly text properties like color, font-family and line-height. Box properties like padding, border and background do not inherit. You can force it with the inherit keyword.

What is the difference between a class selector and an id selector?

A class starts with a dot and can be reused on many elements. An id starts with # and should appear once per page. Ids also have much higher specificity, which is exactly why most teams style with classes only.

What are combinators in CSS?

They describe the relationship between two selectors. A space means any descendant, > means direct child, + means the very next sibling, and ~ means any later sibling.

.card p      { }  /* any p inside .card         */
.card > p    { }  /* only a direct child p      */
h2 + p       { }  /* the p right after an h2    */
h2 ~ p       { }  /* every p after an h2        */

What is the difference between a pseudo-class and a pseudo-element?

A pseudo-class targets a state of an existing element, like :hover, :focus or :nth-child(2). A pseudo-element creates a piece that is not in the HTML, like ::before and ::after. Pseudo-elements use two colons.

What do :is(), :where() and :not() do?

:is() groups selectors and takes the specificity of its strongest argument. :where() does the same grouping but always has zero specificity, so it is easy to override. :not() matches everything except what is inside it.

:is(h1, h2, h3) { margin-block: 0.5em; }
:where(.theme-dark) a { color: #7dd3fc; }
li:not(.active) { opacity: 0.6; }

What are CSS custom properties (variables)?

They are values you define once and reuse. They start with two dashes, are read with var(), and unlike Sass variables they live in the browser, so they can be changed at runtime with JavaScript or inside a media query.

:root {
  --brand: #22c55e;
  --space: 16px;
}
.button {
  background: var(--brand);
  padding: var(--space);
}

Box model and sizing

Almost always asked, in some form.

What is the CSS box model?

Every element is a box made of four layers from inside out: content, then padding, then border, then margin. Padding is space inside the border, margin is space outside it.

What is the difference between content-box and border-box?

With the default content-box, width applies only to the content, so padding and border are added on top and the element ends up wider than you asked. With border-box, width includes padding and border, which is far easier to reason about. Most projects set it globally.

*, *::before, *::after {
  box-sizing: border-box;
}

What is margin collapsing?

When two vertical margins touch, they merge into one and the larger value wins, instead of adding up. It happens between siblings and between a parent and its first or last child. Padding, a border, flexbox or grid all stop it.

What is the difference between visibility: hidden, display: none and opacity: 0?

display: none removes the element completely - no space, no clicks, not read by screen readers. visibility: hidden keeps the space but hides it and blocks clicks. opacity: 0 keeps the space and the element is still clickable and still focusable.

What is the difference between px, em, rem, % and vh/vw?

px is a fixed pixel. em is relative to the font size of the current element, so it compounds when nested. rem is relative to the root font size, so it stays predictable. % is relative to the parent. vh and vw are percentages of the viewport height and width.

Why is rem usually preferred over px for font sizes?

Because rem respects the font size the user has set in their browser. Someone with weak eyesight who increases the default size sees your whole layout scale. Fixed px ignores that setting.

What does the calc() function do?

It lets you mix units in one value and do maths in CSS. Remember to keep spaces around the + and - operators or it will not parse.

.sidebar { width: calc(100% - 240px); }

What do min(), max() and clamp() do?

min() picks the smallest value, max() picks the largest and clamp(min, ideal, max) keeps a value inside a range. clamp is the easiest way to build fluid typography without media queries.

h1 { font-size: clamp(1.75rem, 4vw + 1rem, 3.5rem); }

What is the difference between width: auto and width: 100%?

auto lets the element size itself to the available space after subtracting its own margins, so it fits. 100% means exactly the parent content width, so if the element also has padding or margin and is not border-box, it overflows.

How does overflow work?

overflow decides what happens when content is bigger than the box. visible spills out, hidden clips it, scroll always shows scrollbars, and auto shows them only when needed. You can also set overflow-x and overflow-y separately.

Positioning and stacking

What are the position values in CSS?

static is the default and ignores top/left. relative shifts the element from its normal place but keeps its space. absolute takes it out of flow and positions it against the nearest positioned ancestor. fixed positions it against the viewport. sticky behaves relative until a scroll threshold, then behaves fixed.

What is a positioned ancestor?

It is the closest parent whose position is anything other than static. An absolutely positioned child measures its top, left, right and bottom from that ancestor. If none exists, it uses the page itself.

Why does position: sticky sometimes not work?

Usually for one of three reasons: you did not set top, bottom, left or right; a parent has overflow: hidden or auto, which kills sticky; or the parent is not tall enough for anything to scroll.

.header {
  position: sticky;
  top: 0; /* required */
}

What is z-index and when does it work?

z-index controls which element paints on top. It only works on positioned elements, and on flex or grid children. Higher number means closer to the user.

What is a stacking context?

It is a group of layers that stack together as one unit. Properties like a non-auto z-index on a positioned element, opacity below 1, transform, filter or will-change create one. Inside a stacking context, a child z-index of 9999 still cannot escape above a sibling context with a higher z-index. This is the usual reason a modal hides behind a header.

How do you centre a box horizontally and vertically?

The simplest modern way is flexbox or grid on the parent. The old absolute-position trick still works when you cannot change the parent.

/* modern */
.parent { display: grid; place-items: center; }

/* older */
.child {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

Flexbox

One-dimensional layout - a row or a column.

What is flexbox?

Flexbox lays items out along one axis, either a row or a column, and lets them grow and shrink to fill the space. You set display: flex on the parent and then control the children from there.

What is the difference between the main axis and the cross axis?

The main axis follows flex-direction. With row it goes left to right, with column it goes top to bottom. The cross axis is perpendicular to it. justify-content works along the main axis and align-items works along the cross axis.

What does flex: 1 mean?

It is shorthand for flex-grow: 1, flex-shrink: 1, flex-basis: 0%. Every item with flex: 1 takes an equal share of the free space, no matter how wide its content is.

What is the difference between flex-basis and width?

flex-basis is the starting size along the main axis before growing or shrinking, and it wins over width in a row. width is a plain size and still applies on the cross axis.

What is the difference between align-items and align-content?

align-items aligns items inside a single line on the cross axis. align-content aligns the lines themselves and only has an effect when flex-wrap is on and there is more than one line.

How do you make a flex item stick to the right?

Give it margin-left: auto. An auto margin absorbs all the free space, which is the cleanest way to push one item away from the rest.

.nav { display: flex; gap: 16px; }
.nav .login { margin-left: auto; }

Why does a flex item overflow instead of shrinking?

Because a flex item has min-width: auto by default, so it will not shrink smaller than its content - long text or a big image blocks it. Set min-width: 0 (or overflow: hidden) on the item to allow shrinking.

.flex-child { min-width: 0; }

What does the gap property do?

It adds space between flex or grid items without adding a margin to the outer edges. It replaced the old "margin on every item then remove the last one" hack.

CSS Grid

Two-dimensional layout - rows and columns together.

What is CSS Grid and how is it different from flexbox?

Grid lays out in two dimensions at once, rows and columns. Flexbox handles one dimension. Use grid for the overall page structure and flexbox for the contents of a small component. They work well together.

What is the fr unit?

fr means a fraction of the free space in the grid container. 1fr 2fr gives the second column twice as much of the leftover space as the first.

.layout {
  display: grid;
  grid-template-columns: 240px 1fr;
  gap: 24px;
}

What does repeat(auto-fit, minmax(220px, 1fr)) do?

It creates as many equal columns as fit, where each column is at least 220px and grows to share the space. It gives you a responsive card grid with no media queries at all.

.cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
  gap: 16px;
}

What is the difference between auto-fit and auto-fill?

Both create as many tracks as fit. With auto-fit, empty tracks collapse so the existing items stretch to fill the row. With auto-fill, the empty tracks stay, so items keep their size and leave a gap on the right.

What are grid template areas?

They let you name regions and then draw the layout as text, which is very readable and easy to rearrange in a media query.

.page {
  display: grid;
  grid-template-areas:
    "head head"
    "side main"
    "foot foot";
}
.header { grid-area: head; }
.sidebar { grid-area: side; }

How do you make an item span several columns?

Use grid-column with a span keyword or explicit line numbers. Grid lines are counted from 1, and -1 means the last line.

.featured { grid-column: span 2; }
.full { grid-column: 1 / -1; }

What is the difference between justify-items and justify-content in grid?

justify-items positions the content inside each cell. justify-content positions the whole grid inside the container when the tracks are smaller than the container.

Responsive design

What is responsive web design?

It means one set of HTML and CSS that adapts to any screen size, using fluid widths, flexible images and media queries, instead of building a separate mobile site.

What is a media query?

A block of CSS that only applies when a condition is true - usually a screen width, but it can also check orientation, print, dark mode or reduced motion.

@media (min-width: 768px) {
  .sidebar { display: block; }
}
@media (prefers-color-scheme: dark) {
  :root { --bg: #05080f; }
}

What is mobile-first CSS?

You write the base styles for the smallest screen and then add min-width media queries to enhance for bigger screens. It keeps the mobile CSS small and avoids overriding desktop styles back down.

What are container queries?

They style a component based on the width of its own container instead of the whole viewport. That makes a component truly reusable - the same card can be narrow in a sidebar and wide in the main area without knowing where it is.

.wrapper { container-type: inline-size; }

@container (min-width: 400px) {
  .card { display: grid; grid-template-columns: 120px 1fr; }
}

How do you make an image responsive in CSS?

Set max-width: 100% and height: auto so it never overflows its parent and keeps its aspect ratio. For a fixed-shape box, use object-fit: cover so the image fills the box without stretching.

img { max-width: 100%; height: auto; }
.avatar { width: 64px; height: 64px; object-fit: cover; border-radius: 50%; }

What is prefers-reduced-motion?

A media query that tells you the user has asked their operating system to reduce animation, usually because motion makes them feel unwell. Respecting it is a basic accessibility requirement.

@media (prefers-reduced-motion: reduce) {
  * { animation-duration: 0.01ms !important; transition-duration: 0.01ms !important; }
}

Transitions, animation and performance

What is the difference between a transition and an animation?

A transition animates from one state to another and needs a trigger such as hover or a class change. An animation uses @keyframes, can have many steps, can loop and can start on its own.

.btn { transition: background-color 200ms ease; }

@keyframes pulse {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.4; }
}
.dot { animation: pulse 1.5s infinite; }

Which properties are cheap to animate?

transform and opacity. The browser can handle them on the compositor, often on the GPU, without recalculating layout. Animating width, height, top or margin forces layout on every frame and causes jank.

What are reflow and repaint?

Reflow (layout) is the browser recalculating the position and size of elements - it is expensive. Repaint is redrawing pixels without changing geometry - cheaper. Composite is just moving existing layers - cheapest.

What does will-change do?

It warns the browser that a property is about to change so it can prepare a layer in advance. Use it sparingly and remove it after the animation; too many layers use a lot of memory.

How do you improve CSS performance on a large site?

Keep selectors shallow, avoid deeply nested rules, split CSS so each page loads only what it needs, inline the critical CSS for the first screen, animate only transform and opacity, and remove unused CSS in the build.

What is critical CSS?

The small amount of CSS needed to render the top of the page. Inlining it in the HTML lets the first screen paint before the main stylesheet has downloaded, which improves First Contentful Paint.

Architecture and modern CSS

What is BEM?

BEM stands for Block, Element, Modifier. It is a naming convention: .card is the block, .card__title is an element inside it, and .card--featured is a variation. It keeps specificity flat and makes class names self-explanatory.

What is a CSS preprocessor like Sass?

A tool that adds variables, nesting, mixins, functions and file splitting to CSS, then compiles it to plain CSS. Native CSS now has variables and nesting, so preprocessors are less essential than before.

What are CSS Modules?

A build-time feature where each class name gets a unique hash, so styles cannot leak between components. You import the styles object in your component and use styles.button instead of a global string.

What is Tailwind CSS and what is the trade-off?

Tailwind gives small utility classes like flex, p-4 and text-sm that you compose directly in the markup. You never invent class names and the final CSS stays small, but the HTML becomes long and the team must agree on the approach.

What is the difference between CSS-in-JS and a normal stylesheet?

CSS-in-JS writes styles inside JavaScript, so styles are scoped to the component and can use props. The cost is extra runtime work and a larger bundle unless the library extracts static CSS at build time.

What is the CSS :has() selector?

It is the parent selector people asked for over many years. It styles an element based on what it contains, which used to require JavaScript.

/* a card that contains an image gets extra padding */
.card:has(img) { padding-top: 0; }

/* a label whose checkbox is checked */
label:has(input:checked) { font-weight: 700; }

What is a CSS reset or normalize?

Browsers apply their own default margins and font sizes and they do not agree with each other. A reset removes those defaults, and normalize.css instead makes them consistent while keeping useful ones. Both give you a predictable starting point.

What is the aspect-ratio property?

It keeps a box in a fixed shape while it resizes, replacing the old padding-top percentage hack that was used for responsive video embeds.

.video { width: 100%; aspect-ratio: 16 / 9; }

Continue with another topic

Practise live

CrackInterviewAI listens to the live interview and gives a structured answer on screen for coding, system design, HR and project questions. Download for Windows.