Skip to content

Browser, CSS & Performance

Q (basic): What happens when you type a URL and press Enter?

Say this (30 sec): DNS lookup turns the domain into an IP (with caching at several levels). The browser opens a TCP connection plus TLS handshake for HTTPS (or QUIC for HTTP/3). It sends the HTTP request; the server (or CDN) responds with HTML. The browser parses HTML into the DOM, fetches CSS/JS/images it discovers, builds the CSSOM, runs scripts, builds the render tree, does layout, paints, and composites layers onto the screen.

Follow-ups they ask: Where does a CDN help? → it serves cached content from a server close to the user, cutting latency.

Q (mid): What is the critical rendering path? How do CSS and JS block it?

Say this (30 sec): It’s the steps needed to get the first pixels on screen: DOM + CSSOM → render tree → layout → paint. CSS is render-blocking — the browser won’t paint until CSSOM is ready. A regular <script> is parser-blocking — HTML parsing stops while it downloads and runs. To optimize: inline critical CSS, keep CSS small, use defer or async on scripts, and preload key resources like the hero image or fonts.

Example:

<script src="app.js" defer></script> <!-- downloads in parallel, runs after parsing, in order -->
<script src="analytics.js" async></script> <!-- runs as soon as downloaded, order not guaranteed -->
<link rel="preload" href="/hero.avif" as="image" fetchpriority="high" />

Follow-ups they ask: defer vs async? → both download in parallel; defer runs after HTML parsing in document order; async runs as soon as ready, any order. ES module scripts are deferred by default.

Q (mid): Reflow vs repaint? What triggers them?

Say this (30 sec): Reflow (layout) recalculates positions and sizes — triggered by changing width, height, margin, padding, font size, adding/removing elements, or reading layout properties like offsetHeight after a write. Repaint redraws pixels without layout — color, background, visibility. Reflow is more expensive and can cascade to the whole page. Layout thrashing is alternating reads and writes in a loop, forcing synchronous layout each time.

Example:

// thrashing: read-write-read-write
items.forEach(el => { el.style.width = box.offsetWidth + "px"; });
// fix: batch reads, then writes
const w = box.offsetWidth;
items.forEach(el => { el.style.width = w + "px"; });
Q (basic): Explain the CSS box model and box-sizing.

Say this (30 sec): Every element is a box of content, padding, border and margin. With the default box-sizing: content-box, width applies only to content, so padding and border are added on top. With border-box, width includes padding and border, which is much easier to reason about — that’s why most resets (including Tailwind’s preflight) set border-box globally.

Example:

.box { width: 200px; padding: 20px; border: 2px solid; }
/* content-box: rendered width = 244px; border-box: 200px */

Follow-ups they ask: What is margin collapsing? → vertical margins of adjacent block elements combine into the larger one instead of adding. Doesn’t happen in flex or grid containers.

Q (basic): Flexbox vs Grid?

Say this (30 sec): Flexbox is one-dimensional — lays items out in a row or a column, content-driven; great for navbars, centering, aligning buttons. Grid is two-dimensional — rows and columns together, layout-driven; great for page layouts, card grids, dashboards. They combine well: grid for the page, flex inside components.

Example:

.center { display: flex; justify-content: center; align-items: center; }
.cards { display: grid; grid-template-columns: repeat(auto-fill, minmax(240px, 1fr)); gap: 1rem; }

Follow-ups they ask: justify-content vs align-items in flex? → justify-content aligns along the main axis (row = horizontal), align-items along the cross axis. What does flex: 1 mean? → flex-grow: 1; flex-shrink: 1; flex-basis: 0%.

Q (basic): How does CSS specificity work?

Say this (30 sec): When rules conflict, the more specific selector wins. Think of it as a score (IDs, classes, elements): inline styles beat IDs, IDs beat classes/attributes/pseudo-classes, which beat elements/pseudo-elements. If specificity ties, the rule that comes later wins. !important overrides normal declarations. :where() has zero specificity; :is() and :not() take the specificity of their most specific argument. Cascade layers (@layer) are compared before specificity.

Example:

#nav .link /* (1,1,0) */
.nav a:hover /* (0,2,1) */
ul li a /* (0,0,3) */
Q (basic): Explain position: static, relative, absolute, fixed, sticky.

Say this (30 sec):

  • static — default, normal flow, top/left ignored.
  • relative — normal flow, but can be offset; also becomes the containing block for absolute children.
  • absolute — removed from flow, positioned relative to the nearest positioned ancestor (non-static).
  • fixed — removed from flow, relative to the viewport (unless an ancestor has transform/filter, which becomes its containing block — a common bug).
  • sticky — acts relative until a scroll threshold, then sticks within its parent. Won’t work if an ancestor has overflow: hidden.

Follow-ups they ask: Why isn’t my z-index working? → z-index only works on positioned (or flex/grid) elements, and it’s compared within the same stacking context; transform, opacity < 1, isolation etc. create new stacking contexts.

Q (basic): How do you build responsive designs?

Say this (30 sec): Mobile-first: write base styles for small screens, add min-width media queries for larger. Use fluid units (%, rem, vw, clamp()), flex/grid with wrapping, responsive images (srcset, sizes), and the viewport meta tag. Container queries let a component respond to its container’s width instead of the viewport. In Tailwind, breakpoints like md: are min-width, so unprefixed classes are for mobile.

Example:

h1 { font-size: clamp(1.5rem, 4vw, 3rem); }
@container (min-width: 400px) { .card { flex-direction: row; } }

Follow-ups they ask: rem vs em? → rem is relative to the root font size (predictable); em is relative to the parent’s font size (compounds when nested).

Q (mid): Tailwind CSS — pros and cons?

Say this (30 sec): Pros: fast to build without switching files or naming classes; a consistent design system (spacing, colors) out of the box; only used classes end up in the CSS, so the bundle stays small; no dead CSS; responsive and state variants (md:, hover:, dark:) inline. Cons: long class strings hurt readability; there’s a learning curve; you need patterns for reuse (components, cn() helper with clsx + tailwind-merge); dynamic class names built from strings like bg-${color}-500 don’t get detected. Tailwind v4 moved config into CSS with @theme, has automatic content detection and a much faster engine.

Follow-ups they ask: How does Shadcn UI fit? → It’s not an npm component library — the CLI copies component source into your project, built on Radix primitives (accessible behavior) and styled with Tailwind, so you own and customize the code.

Q (basic): How do you hide an element? Differences?

Say this (30 sec): display: none removes it from layout and the accessibility tree. visibility: hidden hides it but keeps its space. opacity: 0 keeps space and it’s still clickable and read by screen readers. For “visually hidden but available to screen readers”, use the sr-only pattern (Tailwind has a class for it).

Q (basic): What accessibility basics do you follow?

Say this (30 sec):

  • Semantic HTML first: button for actions, a for navigation, nav, main, header, proper heading order — they come with keyboard support and roles for free.
  • Alt text on meaningful images; alt="" on decorative ones.
  • Labels for every input (<label htmlFor>), not just placeholders.
  • Keyboard: everything usable with Tab/Enter/Space/Escape; visible focus styles; trap focus inside modals and return it on close.
  • Color contrast at least 4.5:1 for normal text (WCAG AA).
  • ARIA only when native HTML can’t express it — “no ARIA is better than bad ARIA”.

Common wrong answer: Using a div with onClick as a button. It isn’t focusable or keyboard-activatable without extra tabIndex, role and key handlers.

Q (basic): What are the Core Web Vitals and how do you improve each?

Say this (30 sec):

  • LCP (Largest Contentful Paint) — when the biggest visible element (usually hero image or heading) renders. Good ≤ 2.5s. Improve: fast server/CDN, preload and prioritize the hero image (fetchpriority="high", never lazy-load it), compress images (AVIF/WebP), reduce render-blocking CSS/JS.
  • INP (Interaction to Next Paint) — the delay from a user interaction to the next frame, across the page’s lifetime. Good ≤ 200ms. Improve: break up long tasks, ship less JS, defer non-critical work, useTransition for heavy updates, avoid huge re-renders.
  • CLS (Cumulative Layout Shift) — unexpected layout movement. Good ≤ 0.1. Improve: set width/height or aspect-ratio on images/embeds, reserve space for ads/banners, next/font / font-display with matched fallbacks, don’t insert content above existing content.

Follow-ups they ask: Lab vs field data? → Lighthouse is lab (simulated); CrUX / web-vitals library is field (real users) — Google ranks on field data. Is FID still used? → No, INP replaced FID in March 2024.

Q (basic): What is lazy loading and code splitting?

Say this (30 sec): Lazy loading defers loading something until it’s needed — images below the fold with loading="lazy", components with React.lazy/next/dynamic, data on scroll. Code splitting breaks the JS bundle into chunks so users download only what the current page needs; bundlers split automatically on dynamic import(), and Next.js splits per route automatically.

Example:

<img src="/gallery-1.webp" loading="lazy" width="400" height="300" alt="Gallery photo" />
const { default: confetti } = await import("canvas-confetti"); // loaded on demand
Q (mid): How would you reduce bundle size?

Say this (30 sec): Analyze it first (bundle analyzer, vite-bundle-visualizer). Then: tree-shakeable ESM imports (import { debounce } from "lodash-es" not the whole lodash), replace heavy libs (moment → date-fns/dayjs or Intl), dynamic-import rarely used features, keep code on the server with server components, remove unused dependencies and polyfills, and enable compression (Brotli/gzip).

Q (mid): What is a long task and why does it hurt?

Say this (30 sec): Any main-thread task over 50ms. While it runs, the browser can’t respond to clicks or paint, which hurts INP. Fixes: split work into chunks and yield back to the browser (await scheduler.yield() where supported, or setTimeout(0)), move heavy computation to a Web Worker, and avoid rendering huge lists without virtualization.

Q (basic): localStorage vs sessionStorage vs cookies?

Say this (30 sec):

localStorage sessionStorage Cookies
Lifetime Until cleared Until tab closes Until expiry / session
Size ~5MB per origin ~5MB ~4KB each
Sent to server No No Yes, every request
JS access Yes Yes Yes, unless HttpOnly

Use cookies (with HttpOnly, Secure, SameSite) for auth tokens/sessions so JavaScript can’t read them (protects against XSS theft). Use localStorage for non-sensitive preferences like theme. Both storages are synchronous and store strings only. IndexedDB is for large structured/offline data.

Common wrong answer: “Store the JWT in localStorage, it’s safer.” Any XSS can read localStorage; HttpOnly cookies can’t be read by JS (but then you need CSRF protection, which SameSite=Lax mostly handles).

Q (mid): What do the cookie attributes mean?

Say this (30 sec): HttpOnly — not accessible from JS. Secure — only sent over HTTPS. SameSite=Strict — never sent on cross-site requests; Lax (browser default) — sent on top-level navigations but not cross-site subrequests/POSTs; None — always sent, requires Secure. Domain/Path scope it, Max-Age/Expires set lifetime.

Q (mid): What is CORS? Why do I get a CORS error?

Say this (30 sec): The browser’s same-origin policy blocks JS from reading responses from a different origin (scheme + host + port). CORS is how a server opts in: it responds with Access-Control-Allow-Origin (and related headers). For “non-simple” requests — like PUT/DELETE, JSON Content-Type, or custom headers such as Authorization — the browser first sends an OPTIONS preflight; if the server doesn’t approve, the real request isn’t sent. A CORS error means the server must be configured; it’s not a frontend bug, and Postman/curl don’t enforce CORS.

Example:

Access-Control-Allow-Origin: https://myapp.com
Access-Control-Allow-Methods: GET, POST, PUT
Access-Control-Allow-Headers: Content-Type, Authorization
Access-Control-Allow-Credentials: true

Follow-ups they ask: Can you use * with credentials (cookies)? → No, with credentials: "include" the server must echo a specific origin. Dev fix? → a proxy (Vite server.proxy, Next rewrites) so the request is same-origin.

Q (mid): What are XSS and CSRF, and how are they prevented?

Say this (30 sec): XSS — attacker injects script into your page (e.g. via unescaped user content). React escapes values in JSX by default; danger comes from dangerouslySetInnerHTML, href="javascript:...", and injecting raw HTML — sanitize with DOMPurify and use a Content Security Policy. CSRF — another site makes the user’s browser send an authenticated request using their cookies. Prevent with SameSite cookies, CSRF tokens, and checking the Origin header.

Q (basic): Explain event bubbling, capturing and delegation.

Say this (30 sec): A DOM event travels in three phases: capturing (from window down to the target), target, then bubbling (back up to window). Listeners run in the bubbling phase by default; pass { capture: true } for capturing. Event delegation means attaching one listener on a parent and using event.target to handle events from many children — fewer listeners, and it works for elements added later.

Example:

document.querySelector("#list").addEventListener("click", (e) => {
const item = e.target.closest("li[data-id]");
if (!item) return;
removeItem(item.dataset.id);
});

Follow-ups they ask: stopPropagation vs preventDefault? → stopPropagation stops the event moving to other elements; preventDefault cancels the browser’s default action (form submit, link navigation). target vs currentTarget? → target is where the event originated; currentTarget is the element the listener is attached to. Does React use delegation? → Yes, since React 17 it attaches listeners at the root container.

Q (mid): How do you make animations smooth?

Say this (30 sec): Aim for 60fps (about 16ms per frame). Animate only transform and opacity — they can be handled by the compositor on the GPU without layout or paint. Avoid animating width, height, top, left, margin — they trigger reflow every frame. Use will-change: transform sparingly for elements about to animate. For JS animations, use requestAnimationFrame, not setInterval. Respect prefers-reduced-motion.

Example:

.card { transition: transform 200ms ease, opacity 200ms ease; }
.card:hover { transform: translateY(-4px) scale(1.02); }
@media (prefers-reduced-motion: reduce) { * { animation: none !important; transition: none !important; } }
Q (mid): What is requestAnimationFrame and why use it?

Say this (30 sec): requestAnimationFrame(cb) runs your callback right before the browser’s next repaint, synced to the display’s refresh rate. Unlike setTimeout, it doesn’t drift or run mid-frame, it’s paused in background tabs to save battery, and it gives you a high-resolution timestamp so you can animate based on elapsed time.

Example:

function animate(el, duration) {
const start = performance.now();
function frame(now) {
const progress = Math.min((now - start) / duration, 1);
el.style.transform = `translateX(${progress * 300}px)`;
if (progress < 1) requestAnimationFrame(frame);
}
requestAnimationFrame(frame);
}
Q (mid): GSAP vs CSS animations — when do you use which?

Say this (30 sec): CSS transitions/animations for simple state changes — hover, fade, small enter effects. They’re declarative, zero JS, and can run on the compositor. GSAP when you need control: sequencing with timelines, staggering, scroll-driven animations (ScrollTrigger), pausing/reversing/seeking, animating SVG or JS values, and consistent cross-browser behavior. GSAP runs on requestAnimationFrame and is very optimized, but it’s JS on the main thread, so I still animate transform/opacity (x, y, scale, autoAlpha) rather than layout properties.

Follow-ups they ask: Native alternatives? → Web Animations API (element.animate()), and CSS scroll-driven animations (animation-timeline: scroll()), with growing browser support.

Q (mid): What are IntersectionObserver and ResizeObserver used for?

Say this (30 sec): IntersectionObserver asynchronously tells you when an element enters/leaves the viewport — used for lazy loading, infinite scroll, scroll-triggered animations, and impression tracking — far cheaper than listening to scroll and calling getBoundingClientRect. ResizeObserver notifies when an element’s size changes — for responsive components and charts.