HTML & CSS · Frontend Interview Q&A

HTML & CSS Interview Questions for Frontend Developers: 60 Q&A

Semantic HTML, the box model, specificity you can calculate, positioning and stacking contexts, flexbox vs grid with real layouts, accessibility and responsive design, and how the browser renders it all.

✍️ Pranjal Jain, Ex-Microsoft · IIT Kanpur 📅 10 October 2026 ⏱ 22 min read
Illustration of nested layered boxes beside a grid of cards and flexible rows, representing the CSS box model, grid and flexbox
TL;DR
  • Frontend interviews test HTML and CSS through reasoning questions (specificity, stacking, layout behaviour) and build tasks (a responsive card grid, a modal, a sticky header).
  • Know how to calculate specificity as (IDs, classes/attributes/pseudo-classes, elements), and what :is(), :where() and @layer change.
  • Most "CSS is broken" bugs are stacking contexts (z-index), containing blocks (absolute/fixed), margin collapse, and flex items refusing to shrink (min-width: auto).
  • Flexbox for one dimension and content-driven sizing; grid for two dimensions and layout-driven sizing.
  • Accessibility is no longer optional: semantic elements first, ARIA only when needed, visible focus, 4.5:1 contrast for body text.

HTML and CSS questions are where many strong JavaScript developers lose frontend interviews. They know React well, but cannot explain why z-index: 9999 does nothing, or build a responsive layout without a framework in 30 minutes. Indian product companies hiring frontend engineers (Flipkart, Swiggy, Razorpay, Atlassian, Microsoft and many startups) routinely include a UI round where these fundamentals decide the outcome. This guide covers 60 questions with precise answers and the CSS that proves them.

For the JavaScript and framework half of the same loop, see JavaScript and React interview questions; for the overall learning path, the frontend developer roadmap.

How HTML and CSS Are Tested in Frontend Interviews

Format 1

Concept Q&A

"Explain the box model", "why isn't my z-index working". Answers need precision and an example.

Format 2

Build from a screenshot

Recreate a product card grid, navbar or pricing table in 30-45 minutes, responsive and accessible.

Format 3

Machine coding

A full widget (star rating, tabs, modal, infinite list) where HTML semantics and CSS quality are graded alongside JS. See the machine coding round guide.

HTML Interview Questions (Q1-12)

Q1. What does <!DOCTYPE html> do?

It tells the browser to render in standards mode. Without it, browsers fall back to "quirks mode", emulating old rendering bugs (for example, a different box model for some elements), and your CSS behaves unpredictably.

Q2. What is semantic HTML? Give examples.

Elements that describe meaning: <header>, <nav>, <main> (one per page), <article>, <section>, <aside>, <footer>, <button>, <label>, <time>, <figure>. Screen readers expose landmarks for navigation, search engines understand structure, and native elements come with keyboard and focus behaviour built in.

Q3. Why use a <button> instead of a clickable <div>?

A <button> is focusable with Tab, activates on Enter and Space, announces itself as a button to screen readers, and submits forms. A <div onclick> does none of that; recreating it needs role="button", tabindex="0" and key handlers, and is usually still incomplete. Use links (<a href>) for navigation and buttons for actions.

Q4. article vs section vs div?

<article> is self-contained content that makes sense on its own (a blog post, a product card, a comment). <section> is a thematic grouping, typically with a heading. <div> has no meaning and is for styling hooks only.

Q5. What are the essential tags in <head>?

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Order history | ShopIndia</title>
<meta name="description" content="...">
<link rel="canonical" href="https://example.com/orders">
<link rel="preload" href="https://cdn.example.com/fonts/inter.woff2" as="font" type="font/woff2" crossorigin>
<link rel="stylesheet" href="https://cdn.example.com/app.css">

Without the viewport meta, mobile browsers render at a desktop width (typically 980px) and scale down, breaking every media query.

Q6. script async vs defer vs module?

AttributeBlocks parsing?ExecutesOrder preserved
noneYes, download and executeImmediatelyYes
asyncDownload no; execution may interruptAs soon as downloadedNo
deferNoAfter parsing, before DOMContentLoadedYes
type="module"No (deferred by default)After parsing (or ASAP with async)Yes

Q7. What are data-* attributes?

Custom attributes for storing small bits of data on elements: <li data-order-id="981">, read in JavaScript with el.dataset.orderId and usable in CSS selectors ([data-state="open"]). Do not use them for large data or anything secret.

Q8. How do you build an accessible form field?

<label for="phone">Mobile number</label>
<input id="phone" name="phone" type="tel" inputmode="numeric"
       autocomplete="tel" pattern="[6-9][0-9]{9}" required
       aria-describedby="phone-hint phone-error">
<p id="phone-hint">10-digit Indian mobile number</p>
<p id="phone-error" role="alert" hidden>Enter a valid mobile number</p>

Every input needs a programmatic label (not only placeholder text, which disappears and has poor contrast). Correct type, inputmode and autocomplete give mobile users the right keyboard and autofill. Error messages are linked with aria-describedby so screen readers announce them.

Q9. localStorage vs sessionStorage vs cookies?

localStoragesessionStorageCookies
LifetimeUntil clearedUntil the tab closesSession or explicit expiry
Sent to serverNoNoYes, with every matching request
SizeAround 5 MB per origin (browser dependent)SimilarAbout 4 KB each
JS accessYesYesYes, unless HttpOnly

Do not store auth tokens in localStorage if you can avoid it: any XSS can read them. An HttpOnly; Secure; SameSite cookie is safer for sessions.

Q10. What do loading="lazy", srcset and picture do?

<img src="phone-800.jpg"
     srcset="phone-400.jpg 400w, phone-800.jpg 800w, phone-1600.jpg 1600w"
     sizes="(max-width: 600px) 100vw, 33vw"
     width="800" height="600" loading="lazy" alt="Blue smartphone, front view">

srcset plus sizes lets the browser download the smallest adequate image for the screen and pixel density. loading="lazy" defers offscreen images (never lazy-load the main above-the-fold image, it hurts LCP). width/height reserve space and prevent layout shift. <picture> serves different formats (AVIF, WebP) or art-directed crops.

Q11. What makes good alt text?

Describe the image's purpose in context: "Blue smartphone, front view" on a product page. Decorative images get alt="" so screen readers skip them. Never "image of" or the filename. An icon-only button needs an accessible name on the button, such as aria-label="Close".

Q12. What is the difference between block, inline and inline-block?

Block elements start on a new line and take the full available width; width and height apply. Inline elements flow within text; width and height are ignored and vertical margins do not affect layout. Inline-block flows inline but respects width, height and vertical spacing, useful for badges and buttons in text.

CSS Box Model Interview Questions (Q13-19)

Q13. Explain the box model and box-sizing.

┌──────────────── margin ────────────────┐ │ ┌───────────── border ─────────────┐ │ │ │ ┌────────── padding ─────────┐ │ │ │ │ │ content │ │ │ │ │ │ (width x height) │ │ │ │ │ └────────────────────────────┘ │ │ │ └──────────────────────────────────┘ │ └────────────────────────────────────────┘

With box-sizing: content-box (default), width: 300px; padding: 20px; border: 2px renders 344px wide. With border-box, it renders exactly 300px and the content shrinks to 256px. That is why most resets start with:

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

Q14. What is margin collapsing?

Adjacent vertical margins of block elements in normal flow combine into one margin equal to the larger. A <h2> with margin-bottom: 24px followed by a <p> with margin-top: 16px gives a 24px gap, not 40px. A child's top margin can also "escape" through a parent that has no padding, border or inline content separating them. Margins do not collapse for flex or grid items, floats, absolutely positioned elements, or horizontally. Using gap in flex/grid sidesteps the whole issue.

Q15. Padding vs margin?

Padding is inside the border: it takes the element's background and increases its clickable area. Margin is outside: transparent, and it can collapse or be negative. For button hit areas use padding; for spacing between siblings, prefer the parent's gap.

Q16. display: none vs visibility: hidden vs opacity: 0?

Takes spaceClickableRead by screen readersAnimatable
display: noneNoNoNoNot traditionally
visibility: hiddenYesNoNoYes (discrete)
opacity: 0YesYesYesYes, smoothly

For text visible only to screen readers, use a "visually hidden" utility class (clip, 1px size, overflow hidden), not any of the three.

Q17. What are em, rem, %, vw, vh and dvh?

em is relative to the element's own font size (compounding when nested); rem to the root font size, so it respects user font settings without compounding. % is relative to the parent (for widths) or containing block. vw/vh are 1% of the viewport. On mobile, 100vh can be taller than the visible area because of browser toolbars; dvh (dynamic viewport height) tracks the actual visible height. Use rem for type and spacing, and clamp() for fluid sizes: font-size: clamp(1rem, 0.9rem + 0.5vw, 1.25rem).

Q18. What is overflow, and what does overflow: hidden break?

overflow controls content larger than the box: visible (default), hidden, scroll, auto, and clip. A side effect of hidden/auto: the element becomes a scroll container, which breaks position: sticky descendants (they stick relative to it) and clips dropdowns and tooltips. overflow: clip clips without creating a scroll container.

Q19. How do you make an element keep an aspect ratio?

aspect-ratio: 16 / 9; with a width set. Combine with object-fit: cover on images or video to fill the box without distortion. The old padding-top percentage hack is no longer needed.

CSS Specificity and the Cascade (Q20-26)

Q20. How does the cascade decide which rule wins?

  1. Origin and importance. Normal author styles beat browser defaults; !important declarations beat normal ones (and important user-agent and user styles reverse the order).
  2. Cascade layers. For normal declarations, later @layers beat earlier ones, and unlayered styles beat all layers.
  3. Specificity. Higher specificity wins.
  4. Order of appearance. If all else ties, the later rule wins.

Inline style="" attributes beat any selector of the same importance.

Q21. Calculate the specificity of these selectors.

Selector(IDs, classes/attrs/pseudo-classes, elements)
p(0, 0, 1)
.card .title(0, 2, 0)
ul li.active > a(0, 1, 3)
#nav .item a:hover(1, 2, 1)
input[type="email"]:focus(0, 2, 1)
a::before(0, 0, 2)
:is(#main, .content) p(1, 0, 1): takes the most specific argument
:where(#main, .content) p(0, 0, 1): :where is always zero
*(0, 0, 0)

Compare left to right like version numbers: (1,0,0) beats (0,15,0). Combinators (>, +, ~, space) add nothing.

Q22. Why is !important considered harmful?

It breaks the normal specificity flow, and the only way to override it is another !important with higher specificity, which escalates into an arms race. Legitimate uses: utility classes that must always apply (.hidden), and overriding third-party inline styles you cannot change.

Q23. What are cascade layers (@layer)?

@layer reset, base, components, utilities;

@layer components { .btn { padding: 8px 16px; } }
@layer utilities  { .p-0 { padding: 0; } }   /* wins over .btn despite equal specificity */

Layers make precedence explicit regardless of specificity, which solves the classic "third-party CSS fights my CSS" problem: put vendor styles in an early layer.

Q24. Which properties inherit?

Mostly text-related properties: color, font-*, line-height, text-align, visibility, cursor. Box properties (margin, padding, border, background, width) do not. Force behaviour with inherit, initial, unset or revert.

Q25. Pseudo-classes vs pseudo-elements?

Pseudo-classes select elements in a state: :hover, :focus-visible, :nth-child(2n), :disabled, :has(). Pseudo-elements style a part of an element or generate content: ::before, ::after, ::placeholder, ::marker, ::selection. Single colon for classes, double for elements.

Q26. What does :has() enable?

A "parent selector": style an element based on its descendants or following siblings. .card:has(img) styles cards that contain an image; form:has(input:invalid) .submit dims the submit button while any field is invalid; label:has(+ input:focus) styles a label when its input is focused. Previously all of this needed JavaScript. It is supported in all major modern browsers.

CSS Positioning, z-index and Stacking Contexts (Q27-33)

Q27. Explain the position values.

ValueIn normal flow?Positioned relative toTypical use
staticYesN/A (offsets ignored)Default
relativeYes (space kept)Its own normal positionNudging; anchoring absolute children
absoluteNoNearest positioned ancestor (else the initial containing block)Badges, dropdowns, tooltips
fixedNoViewport (unless an ancestor has transform/filter/perspective)Sticky CTA bars, modals
stickyYesRelative until a threshold in its scroll container, then stuckTable headers, section headings

Q28. Position a "NEW" badge on a product card's corner.

.card  { position: relative; }               /* establishes the containing block */
.badge { position: absolute; top: 8px; right: 8px; }

Forgetting position: relative on the card makes the badge fly to the corner of some ancestor or the page.

Q29. Why is my position: fixed element not fixed to the viewport?

An ancestor with transform, filter, perspective, will-change: transform or contain: paint becomes the containing block for fixed descendants, so they scroll with it. Common when a modal is rendered inside an animated container; render modals at the end of <body> (a React portal) or use the native <dialog> element.

Q30. Why doesn't position: sticky work?

  • No threshold set (top: 0 is required).
  • An ancestor has overflow: hidden, auto or scroll, so it sticks within that box instead of the page.
  • The parent is only as tall as the sticky element, leaving it no room to stick.
  • In a flex container, the item stretches to the full height; add align-self: flex-start.

Q31. What is a stacking context, and why does z-index fail?

A stacking context is an independent layer group; children are stacked within it and the whole group is placed as one unit in its parent context. Created by, among others: the root element; positioned elements with a z-index other than auto; position: fixed or sticky; flex/grid items with a z-index; opacity below 1; transform, filter, mix-blend-mode; isolation: isolate.

.header   { position: relative; z-index: 1; }
.page     { opacity: 0.99; }          /* creates a stacking context at z-index auto level */
.page .tooltip { position: absolute; z-index: 9999; }
/* the tooltip can only stack above things inside .page;
   .page as a whole sits below .header, so the tooltip does too */

The fix is to change the structure (render the tooltip outside), or adjust the z-index of the ancestor that forms the context. A larger number on the child never helps.

Q32. What does isolation: isolate do?

Creates a stacking context with no other visual side effects. Use it on a component root so internal z-indexes (a card's overlay at z-index: 1) cannot leak out and collide with the rest of the page.

Q33. How do you centre an element?

/* Flexbox: horizontally and vertically */
.parent { display: flex; justify-content: center; align-items: center; }

/* Grid: shortest version */
.parent { display: grid; place-items: center; }

/* Absolute + transform: when the element must overlay */
.child { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); }

/* Block element horizontally, with a width */
.child { width: 600px; max-width: 100%; margin-inline: auto; }

Flexbox vs CSS Grid Interview Questions (Q34-43)

Q34. Flexbox vs grid: when to use which?

FlexboxGrid
DimensionsOne (row or column)Two (rows and columns together)
Sizing driven byContent (items grow and shrink)Layout (tracks defined by the container)
Alignment across rowsEach wrapped line is independentItems align in both axes
Best forNavbars, toolbars, button groups, centring, a row of chipsPage layouts, card galleries, dashboards, forms with aligned labels

Q35. What does flex: 1 mean?

flex is shorthand for flex-grow flex-shrink flex-basis. flex: 1 is 1 1 0%: start from zero size and share free space equally, so three flex: 1 items are equal width regardless of content. flex: auto is 1 1 auto: start from content size, then share remaining space, so items with more content end up wider. flex: none is 0 0 auto: rigid.

Q36. Why does my flex item overflow instead of shrinking?

Flex items default to min-width: auto, meaning they will not shrink below their content's minimum size: a long URL, a wide table or a <pre>. Fix with min-width: 0 on the item (or overflow: hidden), then add text-overflow: ellipsis if needed. This single fact solves a large share of real flexbox bugs.

Q37. justify-content vs align-items vs align-content?

justify-content distributes items along the main axis. align-items aligns items on the cross axis within their line. align-content distributes the lines themselves on the cross axis, so it only matters when items wrap onto multiple lines. With flex-direction: column, the axes swap.

Q38. Build a navbar: logo left, links right.

.nav       { display: flex; align-items: center; gap: 16px; padding: 12px 24px; }
.nav .logo { margin-right: auto; }    /* auto margin absorbs all free space */

margin-left: auto / margin-right: auto on a flex item is the cleanest way to push items apart without extra wrappers.

Q39. Build a responsive card grid without media queries.

.grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  gap: 24px;
}

Each column is at least 240px and at most an equal share; the browser fits as many as possible, from one column on phones to five or six on wide screens. The follow-up: auto-fill keeps empty tracks when there are few items (cards stay 240px-ish), while auto-fit collapses empty tracks so the existing cards stretch to fill the row.

Q40. Build a classic page layout with grid template areas.

.page {
  display: grid;
  grid-template-columns: 240px 1fr;
  grid-template-rows: auto 1fr auto;
  grid-template-areas:
    "header  header"
    "sidebar main"
    "footer  footer";
  min-height: 100dvh;
}
header { grid-area: header; }
aside  { grid-area: sidebar; }
main   { grid-area: main; }
footer { grid-area: footer; }

@media (max-width: 768px) {
  .page {
    grid-template-columns: 1fr;
    grid-template-areas: "header" "main" "sidebar" "footer";
  }
}

The footer stays at the bottom on short pages because the middle row is 1fr and the grid is at least the viewport height.

Q41. What is the fr unit?

A fraction of the remaining space in the grid container after fixed tracks and gaps are subtracted. grid-template-columns: 200px 1fr 2fr in an 800px container with no gaps gives 200px, 200px and 400px. Like flex items, 1fr tracks have an automatic minimum, so long content can blow them out; minmax(0, 1fr) fixes it.

Q42. What is subgrid?

grid-template-columns: subgrid (or rows) lets a nested grid reuse its parent's tracks, so the titles, prices and buttons of separate cards line up across a row even when content lengths differ. It is supported in all current major browsers.

Q43. Should you still use floats?

Only for their original purpose: wrapping text around an image. For layout, flexbox and grid replaced floats and the clearfix hacks that came with them.

Responsive Design Interview Questions (Q44-50)

Q44. Mobile-first vs desktop-first?

Mobile-first writes base styles for small screens and adds min-width media queries for larger ones. It keeps the default path simple, matches how most Indian users browse (the majority of traffic on consumer apps is mobile), and tends to produce less CSS to override.

.product-list { display: grid; gap: 12px; }                       /* phones: 1 column */
@media (min-width: 640px)  { .product-list { grid-template-columns: repeat(2, 1fr); } }
@media (min-width: 1024px) { .product-list { grid-template-columns: repeat(4, 1fr); } }

Q45. How do you choose breakpoints?

Based on where your content breaks, not specific devices. Shrink the window until the layout looks wrong and add a breakpoint there. Common ranges cluster around 640, 768, 1024 and 1280px, but they are conventions, not rules.

Q46. What are container queries and why are they a big deal?

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

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

Media queries respond to the viewport; container queries respond to the size of a component's container. The same product card can be vertical in a narrow sidebar and horizontal in a wide main column on the same screen. That makes truly reusable components possible.

Q47. How do you make typography fluid?

clamp(min, preferred, max): h1 { font-size: clamp(1.75rem, 1.2rem + 2.5vw, 3rem); } scales with viewport width but never below 1.75rem or above 3rem. Keep a rem component in the preferred value so user zoom still works.

Q48. How do you handle touch targets and hover on mobile?

Make tap targets comfortably large (WCAG 2.2 sets a minimum of 24 by 24 CSS pixels at level AA, and many design systems use 44-48px). Do not hide essential actions behind hover; use @media (hover: hover) to apply hover-only effects on devices that support hover.

Q49. How do you respect user preferences in CSS?

@media (prefers-reduced-motion: reduce) {
  *, *::before, *::after { animation-duration: 0.01ms !important; transition-duration: 0.01ms !important; }
}
@media (prefers-color-scheme: dark) {
  :root { --bg: #0f1115; --text: #e8e8e8; }
}

Q50. How do CSS custom properties differ from Sass variables?

Sass variables are compiled away. CSS custom properties exist at runtime: they cascade and inherit, can be changed per element or in media queries, and can be updated from JavaScript (el.style.setProperty('--accent', '#0a7')). That makes theming (light/dark, per-brand) possible without recompiling.

Accessibility and Browser Rendering Questions (Q51-60)

Q51. What are the most important accessibility basics?

  • Semantic elements and a logical heading order (one h1, no skipped levels).
  • Everything works with the keyboard; focus order follows visual order.
  • A visible focus indicator. Never outline: none without a replacement; use :focus-visible.
  • Text contrast of at least 4.5:1 for normal text and 3:1 for large text (WCAG AA).
  • Labels for every form control; meaningful alt text; captions for video.
  • Do not convey information by colour alone (red error borders also need text).

Q52. What is ARIA and when should you use it?

ARIA attributes add roles, states and properties for assistive technology (role="tablist", aria-expanded, aria-live). The first rule of ARIA: do not use it if a native element does the job. ARIA changes only what is announced, not behaviour; a div role="button" still needs keyboard handling. Incorrect ARIA is worse than none.

Q53. How do you build an accessible modal?

Prefer the native <dialog> with showModal(): it renders in the top layer, makes the rest of the page inert, closes on Escape and returns focus handling largely for free. Otherwise: role="dialog", aria-modal="true", aria-labelledby pointing at the title, move focus into the dialog on open, trap Tab inside it, close on Escape, and return focus to the trigger on close.

Q54. What is :focus-visible?

It matches when the browser decides focus should be shown, typically keyboard navigation but not mouse clicks. button:focus-visible { outline: 3px solid #1a73e8; outline-offset: 2px; } gives keyboard users a clear ring without showing it on every click, removing the usual excuse for outline: none.

Q55. How does the browser render a page?

HTML ──► DOM ─┐ ├──► Render tree ──► Layout ──► Paint ──► Composite CSS ──► CSSOM┘ (visible (sizes & (pixels (layers to nodes) positions) per layer) screen)

CSS is render-blocking (the browser will not paint until the CSSOM is ready) and synchronous scripts are parser-blocking. Inline critical CSS for above-the-fold content and defer the rest to speed up first paint.

Q56. Reflow vs repaint?

Reflow (layout) recalculates geometry when sizes or positions change: changing width, adding DOM nodes, changing font size. Repaint redraws pixels without geometry changes: colour, background, visibility. Reflow is more expensive and can cascade to the whole page. Reading layout properties (offsetHeight) right after writing styles forces a synchronous reflow; doing that in a loop is "layout thrashing".

Q57. Which CSS properties animate smoothly, and why?

transform and opacity can be handled by the compositor on the GPU without layout or paint, so they stay smooth even when the main thread is busy. Animating top, left, width or height triggers layout every frame. Move things with transform: translate(), scale with transform: scale(). Use will-change sparingly; each promoted layer costs memory.

Q58. What are Core Web Vitals and how does CSS affect them?

Google's Core Web Vitals are LCP (Largest Contentful Paint, loading), INP (Interaction to Next Paint, responsiveness; it replaced FID in 2024) and CLS (Cumulative Layout Shift, visual stability). CSS levers: avoid render-blocking CSS for LCP, reserve space for images, ads and embeds with dimensions or aspect-ratio to prevent CLS, use font-display: swap with size-matched fallbacks to limit font-related shifts, and keep heavy style recalculation off interaction paths for INP.

Q59. BEM vs CSS Modules vs utility-first (Tailwind) vs CSS-in-JS?

ApproachHow it avoids conflictsTrade-off
BEM (.card__title--large)Naming conventionDiscipline-dependent, verbose
CSS ModulesBuild tool generates unique class names per fileNeeds a bundler; theming via variables
Utility-first (Tailwind)Small single-purpose classes, no custom selectorsLong class lists; very consistent design tokens
Runtime CSS-in-JSScoped styles generated in JavaScriptRuntime cost; friction with React Server Components, so zero-runtime options have gained ground

There is no single right answer; interviewers want trade-offs and a reasoned preference.

Q60. How do you debug a CSS layout problem?

  1. Inspect the element. DevTools' computed panel shows which rule won and which were overridden (struck through).
  2. Visualise boxes. Temporarily add outline: 1px solid red to suspects (outline does not affect layout, unlike border).
  3. Use the flex and grid overlays in Chrome or Firefox DevTools to see tracks, gaps and free space.
  4. Check the containing block and stacking context for positioning and z-index bugs (the layers panel helps).
  5. Reduce. Delete rules until the bug disappears; the last one removed is your culprit.

Practice Tasks Before Your Frontend Interview

Build each of these from scratch, without a CSS framework, in under 40 minutes. They cover nearly every question above:

Task 1

Product listing page

Responsive card grid with auto-fill/minmax, a badge positioned on each card, truncated two-line titles, and container-query layouts.

Task 2

Sticky header and sidebar

Sticky table header inside a scrollable panel; then break it with overflow: hidden on an ancestor and explain why.

Task 3

Accessible modal and tabs

Native <dialog> modal and an ARIA tabs widget fully usable with keyboard only. Test with a screen reader (NVDA on Windows, VoiceOver on Mac).

Task 4

Checkout form

Labels, hints, inline errors with aria-describedby, correct input types for mobile, and a visible :focus-visible style.

💡
How to answer CSS questions convincinglyState the rule, give the mechanism, then show the fix. "z-index didn't work because the parent's transform created a stacking context; I moved the tooltip into a portal" beats any definition. When unsure about browser support, say you would check MDN or caniuse rather than guessing. For the full frontend loop, continue with TypeScript interview questions and Next.js interview questions.

Frequently Asked Questions

What is the CSS box model?▾
Every element is a rectangular box made of content, padding, border and margin, from the inside out. With the default box-sizing: content-box, width and height apply to the content only, so padding and border are added on top. With box-sizing: border-box, width and height include padding and border, which is why most stylesheets set border-box globally.
When should I use flexbox vs CSS grid?▾
Use flexbox for one-dimensional layouts where items flow in a row or a column and their size is driven by content, such as navbars, button groups and centring. Use grid for two-dimensional layouts where you control rows and columns together, such as page layouts, card galleries and dashboards. They combine well: grid for the page skeleton, flexbox inside components.
How is CSS specificity calculated?▾
Specificity is compared as three numbers: ID selectors, then class, attribute and pseudo-class selectors, then element and pseudo-element selectors. A selector like #nav .item a:hover scores (1,2,1). Inline styles beat all selectors, !important declarations beat normal ones, :where() contributes zero, and :is() and :not() take the specificity of their most specific argument.
Why is my z-index not working?▾
z-index only applies to positioned elements and to flex or grid items, and it only competes within the same stacking context. If a parent creates a stacking context, for example with opacity below 1, a transform, a filter or position fixed, its children can never appear above elements outside that parent no matter how large their z-index is.
What is the difference between position absolute, fixed and sticky?▾
Absolute removes the element from normal flow and positions it relative to its nearest positioned ancestor. Fixed positions it relative to the viewport, unless an ancestor has a transform or filter, which becomes the containing block. Sticky behaves like relative until the element crosses a threshold such as top: 0 within its scroll container, then sticks; it fails if an ancestor has overflow hidden or the threshold is missing.
What is semantic HTML and why does it matter?▾
Semantic HTML uses elements that describe meaning, such as header, nav, main, article, button and label, rather than generic divs and spans. Screen readers, search engines and browsers rely on that meaning: a real button is focusable and keyboard operable for free, and landmarks let assistive technology users jump between page regions.
What is the difference between async and defer on script tags?▾
Both download the script without blocking HTML parsing. async executes as soon as the download finishes, in any order, which can interrupt parsing, so it suits independent scripts like analytics. defer executes after the document is parsed, in document order, before DOMContentLoaded, which suits app scripts that need the DOM. Module scripts are deferred by default.

Crack Frontend Interviews with Prepflix

Prepflix's interview program covers HTML, CSS, JavaScript and frontend machine coding alongside DSA, with mock rounds modelled on Indian product-company frontend loops.

Explore the Prepflix Course →
Pranjal Jain
Pranjal Jain

Ex-Microsoft SDE · IIT Kanpur · Founder of Prepflix. Helps engineers crack startup and product company interviews across India.