🎨

Top 52 HTML / CSS Interview Questions & Answers (2026)

52 Questions 21 Beginner 20 Intermediate 11 Advanced

About HTML / CSS

Top 50 HTML and CSS interview questions covering semantic markup, box model, layout systems, responsive design, and modern CSS features. Companies hiring for HTML / CSS roles test this knowledge at every stage — from first-round screens that check the basics to final-round conversations about real-world trade-offs.

What to Expect in a HTML / CSS Interview

Expect a mix of conceptual and practical HTML / CSS questions: clear definitions and core-concept checks for junior roles, hands-on scenario questions for mid-level roles, and architecture or trade-off discussions for senior roles. Interviewers usually move from foundational topics toward the kind of problems you'd actually face on the job.

How to Use This Guide

Work through the HTML / CSS questions in order — Beginner, then Intermediate, then Advanced — so each concept builds on the last. Every question has its own page; bookmark the ones that trip you up and revisit them the day before your interview.

Curated by Tech Baithak Editorial Team  ·  Last updated: June 2026

Beginner 21 questions

Core concepts every HTML / CSS developer must know.

01

What is HTML and what does it stand for?

HTML stands for HyperText Markup Language. It is the standard markup language for creating web pages, providing the structure and content of a page. HTML uses elements represented by tags such as <p>, <h1>, and <div> to define different parts of a document including headings, paragraphs, links, images, and forms. Browsers parse HTML and render it as a visual web page. HTML is not a programming language — it is a markup language that describes the structure and meaning of content. It works alongside CSS for styling and JavaScript for interactivity as the three core technologies of the web.

Open this question on its own page
02

What is the difference between HTML and HTML5?

HTML5 is the fifth and current major version of HTML, introducing significant improvements over HTML 4. Key additions include semantic elements like <header>, <nav>, <article>, <section>, and <footer> that describe the purpose of content. HTML5 also introduced native support for audio and video (<audio>, <video>) without plugins like Flash, the <canvas> element for 2D drawing, Web Storage (localStorage/sessionStorage), Geolocation API, Web Workers, and improved form input types (date, email, range). HTML5 also removed deprecated presentational elements like <font> and <center>.

Open this question on its own page
03

What are semantic HTML elements? Give examples.

Semantic HTML elements are tags that convey meaning about the content they contain, both to the browser and to developers. Non-semantic elements like <div> and <span> say nothing about their content. Semantic elements provide context. Examples include <header> (top of a page or section), <nav> (navigation links), <main> (primary content), <article> (self-contained content), <section> (thematic grouping), <aside> (sidebar content), <footer> (bottom of page), <figure> and <figcaption> (media with caption), and <time>. They improve accessibility, SEO, and code readability.

Open this question on its own page
04

What is the DOCTYPE declaration and why is it needed?

The DOCTYPE (Document Type Declaration) is an instruction at the very top of an HTML file that tells the browser which version of HTML the page is written in. In HTML5 it is simply <!DOCTYPE html>. Without a DOCTYPE, browsers enter quirks mode — they emulate old, inconsistent browser behavior to support legacy websites, which can cause unexpected rendering differences across browsers. With a DOCTYPE, browsers use standards mode, applying the CSS box model and layout rules consistently and predictably. It must appear before the <html> tag and is not case-sensitive.

Open this question on its own page
05

What is the difference between &lt;div&gt; and &lt;span&gt;?

The key difference is their default display type. <div> is a block-level element — it takes up the full width available and starts on a new line, making it suitable for grouping and laying out large sections of content. <span> is an inline element — it only takes up as much space as its content and does not break the flow of text, making it suitable for styling or grouping small pieces of text within a line. Both are generic container elements with no semantic meaning (use semantic elements like <section> or <em> when the content has a specific purpose).

Open this question on its own page
06

What is the CSS box model?

The CSS box model describes how every HTML element is rendered as a rectangular box consisting of four areas from inside to outside: content (the actual text or image), padding (space between the content and the border), border (a line surrounding the padding), and margin (space outside the border, separating the element from others). By default (box-sizing: content-box), the width and height properties only apply to the content area, so adding padding and border increases the total element size. With box-sizing: border-box, the width and height include padding and border, making layout calculations much more intuitive — most modern CSS resets apply border-box globally.

Open this question on its own page
07

What is the difference between margin and padding in CSS?

Padding is the space between the element's content and its border — it is inside the element and shares the element's background color. Margin is the space outside the border — it is outside the element and is always transparent, showing the parent's background. Margins from adjacent elements can collapse (the larger margin wins, they don't add up), while padding never collapses. You can click inside an element's padding area (it registers as a click on the element), but not in the margin area. Both can be set on all four sides independently or with shorthand: margin: top right bottom left.

Open this question on its own page
08

What are CSS selectors? List the main types.

CSS selectors are patterns used to target and style HTML elements. The main types are: Element selector (p { }) targets all elements of a type. Class selector (.btn { }) targets elements with a specific class. ID selector (#header { }) targets a unique element by ID. Attribute selector ([type="email"] { }) targets elements with specific attributes. Pseudo-class selector (a:hover { }) targets elements in a specific state. Pseudo-element selector (p::first-line { }) targets a specific part of an element. Combinator selectors like descendant (div p), child (div > p), and sibling (h1 + p) target elements based on their relationship in the DOM.

Open this question on its own page
09

What is CSS specificity?

CSS specificity is the algorithm browsers use to determine which CSS rule wins when multiple rules target the same element and property. It is calculated as a three-part score: [ID count, Class/Attribute/Pseudo-class count, Element/Pseudo-element count]. For example, #nav .link:hover has specificity (1, 2, 0). Higher specificity always wins, regardless of source order — only when specificity ties does the later rule win. Inline styles (style="") override all external/internal CSS. The !important declaration overrides all specificity rules and should be avoided except as a last resort. Understanding specificity is essential for debugging unexpected style overrides.

Open this question on its own page
10

What is the CSS position property and what are its values?

The CSS position property controls how an element is placed in the document flow. static (default): the element follows normal document flow; top/left/right/bottom have no effect. relative: element stays in the normal flow but can be offset with top/left etc. relative to its original position, without affecting surrounding elements. absolute: element is removed from flow and positioned relative to its nearest non-static ancestor. fixed: element is removed from flow and positioned relative to the viewport — it stays put when scrolling. sticky: behaves as relative until the element scrolls to a threshold, then becomes fixed — used for sticky headers.

Open this question on its own page
11

What is Flexbox in CSS?

CSS Flexbox (Flexible Box Layout) is a one-dimensional layout system for distributing space and aligning items in a row or column. Apply it by setting display: flex on a container element. The key properties are: flex-direction (row or column), justify-content (alignment along the main axis: center, space-between, space-around), align-items (alignment along the cross axis: center, stretch, flex-start), flex-wrap (whether items wrap to the next line), and gap (space between items). Flex items can use flex: 1 to fill available space proportionally. Flexbox excels at one-dimensional layouts like navigation bars and card rows.

Open this question on its own page
12

What is CSS Grid?

CSS Grid is a two-dimensional layout system that lets you define rows and columns to position items precisely. Apply it with display: grid on a container. Define the grid structure with grid-template-columns and grid-template-rows: grid-template-columns: repeat(3, 1fr) creates three equal columns. The fr unit represents a fraction of available space. Items are placed automatically or explicitly with grid-column and grid-row. Use gap for spacing between cells. CSS Grid is ideal for full-page layouts, card grids, and any design requiring both row and column control simultaneously.

Open this question on its own page
13

What are CSS media queries?

CSS media queries apply styles conditionally based on the device's characteristics such as screen width, height, orientation, or resolution. Syntax: @media (max-width: 768px) { ... } — styles inside apply only when the viewport is 768px wide or less. Common breakpoints target mobile (max-width: 767px), tablet (768px1024px), and desktop (min-width: 1025px). Use min-width for a mobile-first approach (default styles for mobile, override for larger screens) — this is the recommended pattern. Media queries are the foundation of responsive design, allowing one HTML document to look good on all screen sizes.

Open this question on its own page
14

What is the difference between inline, block, and inline-block display values?

block: the element starts on a new line and stretches to fill the full container width. Width, height, margin, and padding all work as expected. Examples: <div>, <p>, <h1>. inline: the element flows within text, only taking as much width as needed. Vertical margin/padding is ignored; width and height have no effect. Examples: <span>, <a>, <strong>. inline-block: like inline, it flows within text without starting a new line, but unlike inline, it respects width, height, and all margin/padding values. Useful for creating horizontal navigation buttons or grid-like items without Flexbox.

Open this question on its own page
15

What is the CSS float property?

The CSS float property originally enabled text to wrap around images, similar to print layouts. An element with float: left or float: right is removed from the normal document flow and shifted to the specified side; inline content wraps around it. A common problem is that floated elements do not contribute to their parent's height — the parent "collapses." The classic fix is a clearfix hack (.clearfix::after { content: ""; display: table; clear: both; }). While floats were once the primary layout tool, modern CSS layouts use Flexbox and Grid instead. Floats are now mostly used only for their original purpose: text wrapping around images.

Open this question on its own page
16

What are CSS pseudo-classes and pseudo-elements?

Pseudo-classes target elements in a particular state, using a single colon: :hover (mouse over), :focus (has keyboard focus), :active (being clicked), :visited (link visited), :nth-child(n) (positional), :checked (checkbox/radio selected), :disabled. Pseudo-elements target a specific part of an element, using double colons: ::before (inserts content before the element's content), ::after (inserts content after), ::first-line (first line of text), ::first-letter, ::placeholder. The ::before and ::after pseudo-elements are widely used for decorative effects and require a content property to render.

Open this question on its own page
17

What is the CSS z-index property?

The z-index property controls the stacking order of overlapping elements on the z-axis (depth). Elements with a higher z-index appear in front of those with lower values. z-index only works on positioned elements (those with position: relative, absolute, fixed, or sticky) — it has no effect on static elements. A new stacking context is created by elements with non-auto z-index, opacity less than 1, transforms, filters, etc. Elements in a stacking context are stacked independently from elements outside it — a child with z-index: 9999 cannot appear above an element outside its stacking context that has a lower z-index.

Open this question on its own page
18

What is the CSS box-sizing property?

The box-sizing property controls what is included when calculating the width and height of an element. With the default box-sizing: content-box, width and height apply only to the content area — adding padding and border increases the total element size beyond what you set. With box-sizing: border-box, the specified width and height include padding and border, so the element never grows beyond the set dimensions. This makes layout math predictable. It is standard practice to apply *, *::before, *::after { box-sizing: border-box; } globally in your CSS reset so all elements behave consistently.

Open this question on its own page
19

What is responsive web design?

Responsive web design (RWD) is an approach where a website's layout and content adapt to look good on any screen size, from mobile phones to large desktop monitors. The three core principles are: fluid grids (using percentages or fr units instead of fixed pixels), flexible images (max-width: 100% so images never overflow their containers), and media queries (changing styles at specific breakpoints). A mobile-first strategy writes base styles for mobile then uses min-width media queries to add complexity for larger screens. Responsive design replaced separate mobile sites and is now the industry standard approach.

Open this question on its own page
20

What are HTML5 semantic elements and why are they important?

HTML5 introduced elements like <header>, <footer>, <nav>, <main>, <article>, <section>, <aside>, <figure>, and <time> that describe the meaning and purpose of content rather than just its appearance. They matter for three key reasons: Accessibility — screen readers use semantic landmarks to help users navigate pages. SEO — search engines understand content structure better, potentially improving rankings. Maintainability — code is easier to read and understand when structure is expressed semantically. A page built entirely with <div> tags is technically valid but conveys no structural meaning.

Open this question on its own page
21

What is the difference between src and href HTML attributes?

src (source) is used on elements that embed external resources directly into the page — the browser fetches and renders the resource inline. Examples: <img src="photo.jpg">, <script src="app.js">, <iframe src="page.html">. When the browser encounters a src, it pauses HTML parsing to fetch and process the resource. href (hypertext reference) creates a link to an external resource — the browser does not automatically embed the resource. Examples: <a href="page.html"> (navigation link), <link href="style.css" rel="stylesheet"> (CSS link). For the <link> element, the browser fetches the stylesheet but does not pause parsing.

Open this question on its own page
Intermediate 20 questions

Practical knowledge for developers with hands-on experience.

01

How does the CSS cascade work?

The CSS cascade is the algorithm that determines which CSS declaration wins when multiple rules target the same element and property. It evaluates rules in order of priority: 1. Origin and importance — user-agent styles, user styles, author styles (your CSS), and !important declarations in each origin. 2. Specificity — inline styles beat ID selectors, which beat class selectors, which beat element selectors. 3. Source order — when specificity ties, the last rule in the source wins. The cascade enables inheritance (some properties like color and font-size flow down to children by default) and specificity overrides that make component-level styling possible.

Open this question on its own page
02

What is BEM (Block Element Modifier) methodology in CSS?

BEM is a CSS naming convention that creates structured, predictable class names to avoid specificity conflicts and make styles self-documenting. The format is block__element--modifier. A Block is a standalone component: .card. An Element is a part of that block: .card__title, .card__image. A Modifier is a variant or state: .card--featured, .card__title--large. Since all selectors are single classes (no nesting), all rules have equal specificity (0,1,0), completely eliminating specificity battles. BEM is widely used with component-based architectures and works well alongside CSS-in-JS or CSS Modules which enforce scoping automatically.

Open this question on its own page
03

What are CSS custom properties (CSS variables)?

CSS custom properties (also called CSS variables) are user-defined property values that can be reused throughout a stylesheet. Declare them with the -- prefix on a selector (typically :root for global scope): :root { --primary-color: #3490dc; --spacing-lg: 2rem; }. Use them with the var() function: color: var(--primary-color);. Unlike Sass variables (compiled to static values), CSS variables are live in the DOM — they can be changed with JavaScript, overridden in media queries, or scoped to individual components. This makes them powerful for theming (dark mode by redefining variables on body.dark) and design token systems.

Open this question on its own page
04

What is the difference between em, rem, px, vh, and vw units in CSS?

These are different CSS length units with important distinctions. px: absolute pixels — static, not affected by user preferences. em: relative to the current element's font-size — if the element's font-size is 16px, 1.5em = 24px. Nested elements multiply em values, causing "em drift." rem (root em): relative to the root element's font-size (typically 16px) — predictable and no nesting issue. Best for font sizes and spacing. vh (viewport height): 1vh = 1% of the viewport height — 100vh is full screen height. vw (viewport width): 1vw = 1% of viewport width. Use rem for most spacing, vh/vw for full-screen sections and fluid typography.

Open this question on its own page
05

How does Flexbox differ from CSS Grid? When would you use each?

Flexbox is one-dimensional — it lays items in a single row or column and is best for distributing items along one axis. Use it for navigation bars, button groups, centering content, and card rows where the number of items may vary. CSS Grid is two-dimensional — it controls both rows and columns simultaneously and is best for full-page layouts, complex grids, and overlapping elements. The rule of thumb: use Grid when you are thinking about the overall page layout and use Flexbox for component-level layout of items within a container. They are complementary — a Grid layout can contain Flex containers for individual cells.

Open this question on its own page
06

What is the difference between CSS transitions and CSS animations?

CSS transitions animate a property change from one state to another when a trigger occurs (usually a class change or :hover). They are defined by specifying which property to transition, the duration, and the easing: transition: background-color 0.3s ease;. They only have a start and end state. CSS animations use @keyframes to define multiple intermediate states and run automatically without a trigger. They support looping (animation-iteration-count: infinite), direction (alternate), delay, and fill modes. Use transitions for simple hover effects and UI feedback. Use animations for complex, multi-step, or continuously looping effects like spinners, pulses, and entrance animations.

Open this question on its own page
07

What are HTML data attributes (data-*)?

HTML data attributes allow you to embed custom data directly in HTML elements without using non-standard attributes or hidden inputs. Any attribute starting with data- is valid: <div data-user-id="42" data-role="admin">. Access them in JavaScript via the dataset API: element.dataset.userId (camelCase, without the data- prefix). They are useful for storing information that JavaScript needs to interact with an element (IDs, states, configuration) without polluting the class or ID attributes. CSS can also select by data attributes: [data-role="admin"] { color: red; }. They are widely used in Bootstrap components and custom JavaScript interactions.

Open this question on its own page
08

What is ARIA and how does it improve web accessibility?

ARIA (Accessible Rich Internet Applications) is a set of HTML attributes defined by W3C that add accessibility information for assistive technologies like screen readers when native HTML semantics are insufficient. There are three types: Roles define what an element is (role="navigation", role="dialog"). Properties describe characteristics (aria-label="Close dialog", aria-required="true"). States describe current conditions (aria-expanded="true", aria-disabled="true"). The first rule of ARIA is: use native HTML elements whenever possible (<button>, <nav>), as they have built-in semantics. Only use ARIA when native elements cannot achieve the needed behavior.

Open this question on its own page
09

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

All three hide an element visually, but behave very differently. display:none: completely removes the element from the document layout — it takes up no space, is not accessible to screen readers (by default), and cannot receive events. visibility:hidden: the element is invisible but still occupies its space in the layout (a "ghost" effect). It is hidden from screen readers but does not affect document flow. opacity:0: the element is fully transparent but still occupies space, can receive pointer events, and is accessible to screen readers. Use opacity:0 combined with pointer-events:none and aria-hidden="true" for animated show/hide transitions.

Open this question on its own page
10

What are CSS preprocessors (Sass/Less) and what do they add?

CSS preprocessors extend CSS with programming features not available in plain CSS. They compile down to standard CSS. Sass (SCSS syntax) is the most popular and adds: Variables ($primary-color: blue), Nesting (write selectors nested like HTML structure), Mixins (reusable style blocks, like functions), Functions (for calculations), Extend/Inheritance (share rules between selectors), and Partials (split CSS into multiple files and import them). Less is similar but uses a different syntax and runs in the browser or Node. Since CSS now has custom properties and nesting (in modern browsers), the advantage of preprocessors has narrowed, but Sass is still widely used in large projects.

Open this question on its own page
11

What are srcset and sizes attributes for responsive images?

The srcset and sizes attributes on <img> allow the browser to choose the most appropriate image version based on the device's screen resolution and viewport size, saving bandwidth. srcset lists available image files with their widths: srcset="img-400.jpg 400w, img-800.jpg 800w, img-1200.jpg 1200w". sizes tells the browser how wide the image will actually be at different viewport widths: sizes="(max-width: 600px) 100vw, 50vw". The browser calculates which image from the srcset is the smallest one that still looks sharp for the current viewport and DPI. This is critical for mobile performance — serving a 1200px image to a 400px screen wastes data.

Open this question on its own page
12

What is the CSS outline property and how does it differ from border?

Both outline and border draw a line around an element, but with important differences. Border is part of the box model — it takes up space and affects the element's layout. Outline is drawn outside the border and does not take up space — it does not affect the element's dimensions or surrounding layout. Outlines cannot have different widths per side (no outline-top) and cannot have rounded corners (though outline-offset can space it away). The most important use of outline is for keyboard focus indicators: browsers add an outline to focused elements by default for accessibility. Never use outline: none without providing an alternative focus style, as it harms keyboard navigation accessibility.

Open this question on its own page
13

What is the critical rendering path in browsers?

The critical rendering path is the sequence of steps a browser takes from receiving HTML bytes to rendering pixels on screen. The steps are: 1. Parse HTML into the DOM tree. 2. Parse CSS into the CSSOM tree. The browser blocks rendering until all CSS is downloaded and parsed (CSS is render-blocking). 3. Combine DOM and CSSOM into the Render Tree (only visible elements). 4. Layout: calculate each element's size and position. 5. Paint: draw pixels to layers. 6. Composite: assemble layers. To optimize it: inline critical CSS, defer non-critical CSS, use <link rel="preload"> for key resources, and place <script> tags at the end of <body> or use async/defer.

Open this question on its own page
14

What are web fonts and how do you use @font-face?

Web fonts allow you to use custom typefaces beyond the limited set of system fonts. The @font-face rule declares a font family by specifying a name and the URL of the font file: @font-face { font-family: 'MyFont'; src: url('myfont.woff2') format('woff2'); }. The woff2 format offers the best compression and is supported in all modern browsers. Services like Google Fonts host fonts and provide a <link> tag you paste into your HTML. Performance considerations: use font-display: swap to show a fallback font while loading, apply font-display: optional for less critical fonts, and self-host fonts to reduce DNS lookups.

Open this question on its own page
15

What is CSS Grid's fr unit?

The fr (fractional unit) is a CSS Grid-specific unit that represents a fraction of the available free space in the grid container. After fixed sizes and min-content requirements are satisfied, remaining space is distributed proportionally using fr units. grid-template-columns: 1fr 1fr 1fr creates three equal columns. grid-template-columns: 2fr 1fr creates two columns where the first is twice the width of the second. repeat(3, 1fr) is a convenient shorthand. The fr unit differs from percentages because it accounts for gap spacing — 1fr fills available space after gaps, while 33.33% does not account for gaps and can cause overflow.

Open this question on its own page
16

What is the CSS object-fit property?

object-fit controls how a replaced element (primarily <img> and <video>) is scaled and positioned within its container when the element's intrinsic aspect ratio differs from the container's. fill (default): stretches to fill, potentially distorting the image. contain: scales to fit entirely within the box, preserving aspect ratio — may leave empty space ("letterbox"). cover: scales to fill the box entirely, preserving aspect ratio — may crop edges. This is the most commonly used value for hero images and avatars. none: no scaling. scale-down: smaller of none or contain. Pair with object-position (like background-position) to control where the image is cropped.

Open this question on its own page
17

What is the CSS transform property?

The CSS transform property applies 2D or 3D transformations to an element without affecting document flow — other elements do not reflow around the transformed element. Common functions: translate(x, y) moves the element (GPU-accelerated when combined with will-change). scale(x, y) resizes. rotate(angle) rotates. skew(x, y) slants. matrix() applies a full transformation matrix. Multiple functions chain: transform: translateX(50px) rotate(45deg) scale(1.2). A key benefit for animation: transforms and opacity are the only CSS properties that browsers can animate on the GPU compositor thread, avoiding main-thread layout recalculations and enabling smooth 60fps animations.

Open this question on its own page
18

What are HTML meta tags and what are they used for?

HTML meta tags in the <head> provide metadata about the page — information not displayed on the page but used by browsers, search engines, and social platforms. Key meta tags: <meta charset="UTF-8"> declares the character encoding. <meta name="viewport" content="width=device-width, initial-scale=1"> is critical for responsive design — it tells mobile browsers to use the device's actual width rather than zooming out to a virtual 980px viewport. <meta name="description" content="..."> provides the snippet text for search results. Open Graph tags (<meta property="og:title"> etc.) control how links appear when shared on social media.

Open this question on its own page
19

What are CSS Logical Properties?

CSS Logical Properties are an alternative to physical directional properties (margin-left, padding-top) that use logical directions relative to the writing mode and text direction. In a left-to-right horizontal layout: inline-start = left, inline-end = right, block-start = top, block-end = bottom. Examples: margin-inline-start, padding-block-end, border-inline. They are critical for internationalization — a layout using logical properties automatically flips correctly for right-to-left languages (Arabic, Hebrew) without additional media queries. Modern CSS recommends logical properties for any layout that may need to support multiple writing modes.

Open this question on its own page
20

What is the :root pseudo-class in CSS and what is it used for?

The :root pseudo-class matches the root element of the document, which in HTML is the <html> element. It has higher specificity than the html element selector. Its primary use is declaring CSS custom properties (variables) that are globally accessible throughout the stylesheet: :root { --primary: #3490dc; --radius: 8px; }. Variables declared on :root are available to every element. It is also a convenient place for global resets and font size definitions. Many design systems and component libraries declare all their design tokens on :root, enabling easy theming by overriding these variables.

Open this question on its own page
Advanced 11 questions

Deep expertise questions for senior and lead roles.

01

What are CSS container queries and how do they differ from media queries?

CSS Container Queries (CSS Containment Level 3) allow you to apply styles based on the size of a parent container rather than the viewport. Declare a containment context: .card-container { container-type: inline-size; }. Then query it: @container (min-width: 400px) { .card { ... } }. This solves a fundamental problem with media queries: a component like a card should adapt to its own container's width, not the viewport — the same card might be in a sidebar (narrow) and in a main column (wide) simultaneously. Container queries enable truly reusable, self-contained responsive components that are container-aware rather than viewport-aware.

Open this question on its own page
02

What is the CSS @layer at-rule?

CSS @layer (Cascade Layers) allows you to explicitly define the order of specificity precedence between groups of styles. Declare layers: @layer base, components, utilities;. Styles in later-declared layers always win over earlier layers, regardless of specificity. This solves the common problem of utility classes (like Tailwind) needing !important to override component styles. Example: a .text-red utility class with specificity (0,1,0) in the utilities layer will always beat a .card .title rule with specificity (0,2,0) in the components layer, because the utilities layer is declared last. @layer gives CSS authors explicit, deterministic control over the cascade beyond specificity.

Open this question on its own page
03

What is the Shadow DOM and what problem does it solve?

The Shadow DOM is a web standard that encapsulates a component's internal DOM structure and styles, hiding them from the main document. Styles inside a Shadow DOM do not leak out and external styles do not bleed in — providing true style encapsulation. This solves the global CSS namespace problem: a component's .button class is scoped only to that component's shadow tree. Shadow DOM is the foundation of Web Components (custom elements). Native browser elements like <video>, <input type="range">, and <select> use Shadow DOM internally to render their complex internal structure. It can be attached via JavaScript: element.attachShadow({ mode: "open" }).

Open this question on its own page
04

What are CSS Houdini APIs?

CSS Houdini is a set of low-level browser APIs that expose the CSS engine internals to JavaScript, allowing developers to extend CSS with custom behaviors that were previously impossible without JavaScript hacks. Key APIs include: Paint API: define a registerPaint() worklet to draw custom backgrounds, borders, or images directly with the Canvas API. Layout API: create entirely custom layout algorithms (like Masonry). Animation Worklet: create timeline-driven animations that run on the compositor thread. Properties and Values API (CSS.registerProperty()): register custom properties with types, enabling CSS transitions on custom properties. Houdini moves extensibility from "JS-powered class toggling" to "native browser rendering pipeline."

Open this question on its own page
05

What is the difference between browser reflow and repaint?

Reflow (also called layout) occurs when the browser must recalculate the position and dimensions of elements. It is triggered by changes that affect layout geometry: adding or removing elements, changing width/height/margin/padding/font-size, reading layout properties like offsetWidth in JavaScript. Reflow is expensive because it may cascade through the entire document. Repaint occurs when an element's appearance changes without affecting layout: changing color, background-color, visibility, or outline. Repaints are cheaper than reflows but still cost GPU cycles. Compositing is the cheapest: only transform and opacity changes can be handled entirely by the compositor thread without triggering reflow or repaint on the main thread.

Open this question on its own page
06

What are CSS :is(), :where(), and :has() selectors?

:is() is a forgiving selector list function: :is(h1, h2, h3) a matches links inside any heading without writing three separate rules. Its specificity equals the most specific selector in its argument. :where() works identically to :is() but its specificity is always zero — ideal for base/reset styles that should be easy to override. :has() is the long-awaited "parent selector": label:has(+ input:invalid) styles a label when the adjacent input is invalid. :has(img) matches containers that contain an image. It enables previously impossible CSS patterns that required JavaScript. :has() is now supported in all modern browsers (Chrome 105+, Safari 15.4+, Firefox 121+).

Open this question on its own page
07

What is CSS containment and the contain property?

CSS containment lets you isolate a subtree of the page from the rest of the document, enabling browser performance optimizations. The contain property takes values: layout: the element's internal layout does not affect the rest of the page (no layout escape). paint: the element's descendants are not drawn outside its borders. size: the element's size does not depend on its children. style: scopes counter and quote properties. content is shorthand for layout + paint. strict is shorthand for layout + paint + size. Container queries require contain: layout or inline-size. Containment helps browsers avoid recalculating layout or repainting the entire page when a contained component changes.

Open this question on its own page
08

What is the CSS aspect-ratio property?

The aspect-ratio property maintains a specific width-to-height ratio for an element regardless of its actual dimensions, preventing layout shift. aspect-ratio: 16 / 9 keeps an element in 16:9 proportions. Before this property existed, developers used the "padding-top hack" (padding-top: 56.25%) to create aspect-ratio boxes. aspect-ratio: 1 / 1 creates perfect squares, useful for avatars and thumbnail grids. If both width and height are set, aspect-ratio is ignored. If only one dimension is set, the other is calculated from the ratio. It works with intrinsic ratios from replaced content — the aspect-ratio overrides only when the content does not have its own ratio.

Open this question on its own page
09

What is CSS subgrid and how does it work?

CSS subgrid allows a grid item that is itself a grid container to inherit its parent's grid tracks rather than defining its own. Without subgrid, a nested grid always creates independent tracks — its children cannot align to the outer grid. With grid-template-columns: subgrid, the nested container uses the parent's column tracks directly. A classic use case is card grids where each card has a header, body, and footer — with subgrid, all card footers align to the same row across the entire grid without fixed heights. Subgrid is supported in all major browsers as of 2023 (it was the last major CSS Grid feature to be fully implemented). It solves one of the most requested CSS layout challenges.

Open this question on its own page
10

What is the CSS will-change property and when should it be used?

The will-change property is a hint to the browser that an element's specified properties are about to change, allowing it to set up hardware acceleration optimizations in advance. Example: will-change: transform, opacity causes the browser to promote the element to its own GPU compositor layer before the animation starts, preventing the jank of a mid-animation layer promotion. When to use it: sparingly, only on elements you know will animate, and only when you have measured a performance problem. When NOT to use it: do not apply it to everything globally — each will-change layer consumes GPU memory. Apply it just before an animation (via JS) and remove it afterwards. It is a last resort optimization tool, not a default setting.

Open this question on its own page
11

What are Web Components and what standards make them up?

Web Components are a suite of native browser standards that enable creating reusable, encapsulated HTML elements. They consist of three main specifications: Custom Elements: define new HTML tags with custom behavior using customElements.define("my-button", MyButtonClass). The class extends HTMLElement and can implement lifecycle callbacks (connectedCallback, disconnectedCallback, attributeChangedCallback). Shadow DOM: encapsulate the internal structure and styles within a shadow root, preventing style leakage. HTML Templates: <template> and <slot> elements define reusable, inert HTML fragments and slots for external content. Web Components are supported natively in all major browsers and work with any framework or no framework at all.

Open this question on its own page
Back to All Topics 52 questions total