Master these 31 carefully curated interview questions to ace your next Html interview.
HTML5 is the latest HTML version with semantic elements, native multimedia, canvas, local storage, and new form types.
New features: semantic elements (header, nav, article, section, footer), audio/video tags, canvas for graphics, geolocation API, localStorage/sessionStorage, web workers, new input types (email, date, range), form validation attributes, drag and drop API.
Semantic elements describe their meaning: header, nav, main, article, section, aside, footer — improving accessibility and SEO.
Non-semantic: div, span (no meaning). Semantic: header (introductory), nav (navigation), main (primary content), article (independent content), section (thematic grouping), aside (tangential), footer, figure/figcaption. Benefits: screen readers understand structure, search engines index better.
Block elements take full width and start new lines (div, p); inline elements flow within text (span, a, strong).
Block: full width, stack vertically, can contain block/inline. Examples: div, p, h1-h6, ul, section. Inline: width of content, flow horizontally. Examples: span, a, strong, em, img, input. Inline-block: flows inline but accepts width/height. CSS display property can change behavior.
The DOM (Document Object Model) is a tree API representing HTML documents that JavaScript can read and manipulate.
Browser parses HTML into a tree of nodes. JavaScript accesses via document.getElementById(), querySelector(), createElement(). DOM manipulation triggers reflow and repaint. Virtual DOM (React) batches updates for performance. Shadow DOM encapsulates component styles.
localStorage persists forever (5MB); sessionStorage clears on tab close; cookies sent with HTTP requests (4KB) and can expire.
localStorage: key-value, 5-10MB, persists until cleared. sessionStorage: same but cleared on tab close. Cookies: 4KB, sent with every HTTP request, can set expiry, domain, path, Secure, HttpOnly, SameSite flags. Use cookies for auth tokens; localStorage for preferences.
Use semantic HTML, alt text, ARIA attributes, keyboard navigation, color contrast, and screen reader testing.
WCAG guidelines: (1) Semantic HTML. (2) Alt text for images. (3) ARIA roles and labels. (4) Keyboard navigation. (5) Color contrast 4.5:1. (6) Focus indicators. (7) Form labels. (8) Skip navigation link. (9) Responsive design. Tools: Lighthouse, axe DevTools.
Default blocks parsing; async downloads parallel and executes immediately; defer downloads parallel and executes after DOM parsing.
<script>: blocks HTML parsing. <script async>: downloads in parallel, executes when ready (may run before DOM complete). <script defer>: downloads in parallel, executes after parsing, maintains order. Best practice: defer for DOM-dependent scripts, async for independent scripts (analytics).
Web Components are custom reusable elements using Custom Elements, Shadow DOM, and HTML Templates — framework agnostic.
Custom Elements: define new HTML tags with customElements.define(). Shadow DOM: encapsulated DOM with scoped CSS. HTML Templates: template and slot elements. Lifecycle: connectedCallback, disconnectedCallback, attributeChangedCallback. Lit library simplifies development. Works with any framework.
The sequence browsers use to convert HTML/CSS/JS into pixels: DOM → CSSOM → Render Tree → Layout → Paint → Composite.
Optimization: minimize critical resources, reduce critical path length, minimize bytes. Inline critical CSS, defer non-critical CSS/JS, preload key resources, use font-display: swap. Tools: Lighthouse, WebPageTest.
Audit with Lighthouse/axe, fix heading hierarchy, add alt text, ensure keyboard nav, improve color contrast, add ARIA labels.
Systematic: (1) Fix heading hierarchy. (2) Add landmark elements. (3) Alt text for images. (4) Label form inputs. (5) Ensure 4.5:1 contrast. (6) Add skip nav link. (7) Test keyboard-only navigation. (8) Add ARIA labels for icon buttons. (9) Test with screen reader. Target: 100 Lighthouse score.
Proper headings, semantic elements, meta tags, structured data, and accessible markup significantly improve search rankings.
SEO HTML: (1) Single H1 with keyword. (2) Proper heading hierarchy. (3) Unique title and meta description. (4) Semantic elements for crawler understanding. (5) Schema.org JSON-LD. (6) Canonical URLs. (7) Alt text for images. (8) Internal linking. (9) Mobile-friendly responsive design.
Semantic HTML uses meaningful tags like header, nav, article, section that describe content purpose rather than just appearance.
Semantic elements convey meaning to browsers, screen readers, and search engines. Examples: <header> for page/section headers, <nav> for navigation, <main> for primary content, <article> for self-contained content, <section> for thematic grouping, <aside> for tangential content, <footer> for footer info. Benefits: better accessibility (screen readers navigate by landmarks), improved SEO (search engines understand content structure), easier maintenance, and clearer code. Avoid using <div> for everything — choose semantic elements first.
div is a block-level container that takes full width; span is an inline container that wraps text without breaking flow.
div: block-level, starts new line, takes full width, used for layout sections. span: inline, flows within text, takes only needed width, used for styling text portions. div can contain block and inline elements; span should only contain inline content. Neither has semantic meaning — they're generic containers. Use div for page structure (but prefer semantic elements). Use span for styling text within paragraphs. CSS display property can change their default behavior.
Forms collect user input using elements like input, textarea, select, and button, submitted via action URL and method.
Form attributes: action (submission URL), method (GET/POST), enctype (multipart/form-data for files). Input types: text, email, password, number, date, checkbox, radio, file, range, color, tel, url. textarea for multiline text. select/option for dropdowns. label (for attribute links to input id) — critical for accessibility. fieldset/legend groups related inputs. required, pattern, minlength, maxlength for validation. FormData API in JavaScript for programmatic form handling. autocomplete attribute for browser autofill.
The alt attribute provides alternative text for images, used by screen readers and displayed when images fail to load.
alt text serves: (1) Accessibility — screen readers read alt text to visually impaired users. (2) Fallback — displays when image fails to load or is blocked. (3) SEO — helps search engines understand image content. Best practices: be descriptive and concise (125 chars), don't start with 'image of', describe function for interactive images, use empty alt='' for decorative images. Missing alt is an accessibility violation (WCAG 2.1). Long descriptions use aria-describedby.
Data attributes (data-*) store custom data on HTML elements, accessible via JavaScript's dataset property.
Syntax: data-user-id='123'. Access: element.dataset.userId (camelCase conversion). Use cases: storing metadata, configuration for JS plugins, passing data to event handlers, CSS selectors ([data-active]). Benefits: keeps HTML valid (custom attributes without data- prefix are invalid), separates data from presentation. CSS can select: [data-status='active'] { color: green }. Don't store sensitive data (visible in DOM). Alternative to hidden inputs for embedding data. Common in frameworks: React uses data attributes for internal tracking.
Canvas provides a drawable area for rendering 2D/3D graphics via JavaScript using the Canvas API or WebGL.
2D context: canvas.getContext('2d'). Methods: fillRect, strokeRect, arc, lineTo, drawImage, fillText. Pixel manipulation: getImageData/putImageData. WebGL context: canvas.getContext('webgl') for 3D graphics. Use cases: games, data visualizations, image editing, animations, generative art. Canvas is resolution-dependent (bitmap) vs SVG (vector, scalable). Performance: requestAnimationFrame for smooth animation. OffscreenCanvas for worker-thread rendering. Accessibility: provide fallback content inside canvas tags.
localStorage persists indefinitely (5MB), sessionStorage clears on tab close (5MB), cookies expire and are sent with requests (4KB).
localStorage: persists until cleared, 5-10MB, same-origin, not sent to server. sessionStorage: same as localStorage but cleared when tab closes, isolated per tab. Cookies: 4KB, sent with every HTTP request, can set expiry/path/domain, HttpOnly prevents JS access, Secure requires HTTPS, SameSite controls cross-site sending. Use localStorage for preferences/theme. Use sessionStorage for form drafts. Use cookies for auth tokens (HttpOnly, Secure, SameSite=Strict). IndexedDB for structured data (hundreds of MB).
Web Components are custom HTML elements with encapsulated markup and styles using Custom Elements, Shadow DOM, and templates.
Three technologies: (1) Custom Elements: define new HTML tags via customElements.define('my-component', class). (2) Shadow DOM: encapsulated DOM tree with scoped styles — no CSS leaking in or out. (3) Templates: <template> and <slot> for reusable markup. Lifecycle callbacks: connectedCallback, disconnectedCallback, attributeChangedCallback. Shadow DOM modes: open (accessible via element.shadowRoot) and closed. Used by most UI frameworks internally. Libraries: Lit, Stencil simplify development. Native browser support, no framework needed.
Lazy loading defers loading of off-screen images and iframes using loading='lazy' attribute until they approach the viewport.
Native: <img loading='lazy'> and <iframe loading='lazy'>. Browser determines when to load based on scroll position and network conditions. Benefits: faster initial page load, reduced bandwidth, better Core Web Vitals (LCP not affected if above-fold images use loading='eager'). Don't lazy-load above-the-fold images. For JS-based lazy loading: IntersectionObserver API. placeholder/blur-up technique: show low-quality image placeholder, swap to full image on load. fetchpriority='high' for critical images.
ARIA (Accessible Rich Internet Applications) adds attributes to HTML elements to provide accessibility information to assistive technologies.
ARIA roles: role='navigation', role='dialog', role='alert', role='tab'. States: aria-expanded, aria-selected, aria-checked, aria-disabled. Properties: aria-label, aria-describedby, aria-labelledby, aria-live. Landmark roles structure page: banner, main, navigation, contentinfo. First rule of ARIA: don't use ARIA if native HTML provides the semantics. aria-live='polite' for dynamic content updates (screen readers announce changes). aria-hidden='true' hides elements from screen readers. WCAG 2.1 AA is the standard compliance level.
Meta tags provide metadata about the page to browsers and search engines, including description, viewport, charset, and Open Graph.
Essential: <meta charset='UTF-8'>, <meta name='viewport' content='width=device-width, initial-scale=1'>. SEO: <meta name='description' content='...'> (150-160 chars), <title> (50-60 chars). Social: og:title, og:description, og:image (Open Graph for Facebook), twitter:card (Twitter Cards). Robots: <meta name='robots' content='index, follow'>. Security: Content-Security-Policy, X-Content-Type-Options. Canonical: <link rel='canonical' href='...'> prevents duplicate content. Structured data via JSON-LD for rich snippets.
CSP is a security header/meta tag that restricts which resources can load on a page, preventing XSS and injection attacks.
Set via HTTP header or <meta http-equiv='Content-Security-Policy'>. Directives: default-src (fallback), script-src (JS sources), style-src (CSS sources), img-src, connect-src (AJAX/WebSocket), font-src, frame-src. Values: 'self' (same origin), 'none', 'unsafe-inline' (avoid), 'unsafe-eval' (avoid), nonce-based, hash-based. report-uri collects violation reports. Start with Content-Security-Policy-Report-Only to test. Strict CSP: script-src 'nonce-{random}' blocks all inline scripts without matching nonce.
The browser constructs DOM from HTML, CSSOM from CSS, combines into render tree, calculates layout, then paints pixels.
Steps: (1) Parse HTML → DOM tree. (2) Parse CSS → CSSOM tree. (3) JavaScript execution (may modify DOM/CSSOM). (4) Combine DOM + CSSOM → Render Tree (only visible nodes). (5) Layout: calculate exact position and size of each node. (6) Paint: fill pixels (text, colors, images, borders). (7) Composite: layer ordering for overlapping elements. CSS is render-blocking; JS is parser-blocking (unless async/defer). Optimize: minimize critical resources, reduce critical path length, minimize critical bytes. Preload critical assets.
Use semantic HTML, proper heading hierarchy, alt text, keyboard navigation, color contrast, ARIA labels, and screen reader testing.
Checklist: (1) Semantic HTML (nav, main, article). (2) Heading hierarchy (h1→h2→h3). (3) Alt text for all images. (4) Keyboard navigation (tab order, focus styles). (5) Color contrast ratio ≥ 4.5:1 (WCAG AA). (6) Form labels linked to inputs. (7) Skip navigation link. (8) ARIA for dynamic content. (9) Responsive text (rem units). (10) Captions for video/audio. (11) Focus management for modals/SPAs. Tools: axe DevTools, Lighthouse accessibility audit, NVDA/VoiceOver testing. Test with keyboard-only navigation.
Defer/async scripts, lazy load images, preload critical resources, minimize DOM size, and use responsive images.
HTML optimizations: (1) <script defer> for non-critical JS. (2) <link rel='preload'> for critical CSS/fonts. (3) <img loading='lazy'> for below-fold images. (4) <picture> with srcset for responsive images. (5) Minimize DOM depth and node count (<1500 nodes ideal). (6) Inline critical CSS in <head>. (7) Remove unused HTML/comments. (8) Use <link rel='preconnect'> for third-party domains. (9) DNS prefetch for expected navigations. (10) Compress with gzip/brotli. (11) Set proper cache headers. (12) Use CDN for static assets.
Proper heading hierarchy (h1→h2→h3) creates document outline, improves accessibility, SEO, and content organization.
Rules: one h1 per page (main topic), h2 for major sections, h3 for subsections — never skip levels. Screen readers use headings for navigation (users jump between headings). Search engines use headings to understand content hierarchy and relevance. Don't use headings for styling — use CSS. Outline algorithm: headings create a logical document structure. Testing: HTML5 Outliner tools show your document structure. Impact on SEO: proper headings with keywords improve rankings. WCAG 2.1 Success Criterion 1.3.1 requires meaningful structure.
SVG is vector-based XML with DOM access and scalability; Canvas is pixel-based bitmap rendering via JavaScript API.
SVG: XML-based, scalable without pixelation, DOM accessible (CSS styling, event handlers per element), good for icons/charts/logos, resolution-independent, larger file for complex graphics. Canvas: pixel-based, JavaScript API for drawing, no DOM for drawn elements, better for games/animations/pixel manipulation, resolution-dependent, better performance for many objects. Choose SVG for: UI elements, icons, charts, accessible graphics. Choose Canvas for: games, real-time visualizations, image processing, particle effects.
Use srcset attribute for different resolutions, sizes attribute for viewport-based sizing, and picture element for art direction.
srcset with width descriptors: <img srcset='small.jpg 480w, large.jpg 1024w' sizes='(max-width: 600px) 480px, 1024px'>. Browser selects best image based on viewport and DPR. picture element: <picture><source media='(min-width: 800px)' srcset='wide.jpg'><img src='fallback.jpg'></picture> — different images for different viewpoints (art direction). Format fallback: <source type='image/webp' srcset='img.webp'><source type='image/jpeg' srcset='img.jpg'>. Always include img as fallback. loading='lazy' for off-screen images.
Use table-based layout, inline CSS, avoid JavaScript and modern CSS, test across email clients, and keep width under 600px.
Email HTML is stuck in early 2000s due to client limitations. Rules: (1) Table-based layout (flexbox/grid not supported in Outlook). (2) Inline CSS (many clients strip <style> tags). (3) No JavaScript. (4) Max width 600px. (5) System fonts or web-safe fonts. (6) Images: absolute URLs, alt text, some clients block by default. (7) No position, float (limited), background images (MSO conditional comments for Outlook). (8) Test: Litmus, Email on Acid. (9) Use MJML or Foundation for Emails frameworks. (10) Dark mode: meta tag + prefers-color-scheme.
Ready to master Html?
Start learning with our comprehensive course and practice these questions.