Skip to content
Tutorials Center
My learning

Topics

Lesson 122 of 122 ยท Practice and Review

HTML Interview Questions

Prepare for front-end interviews with 36 HTML questions and clear answers, grouped by level, covering semantics, forms, media, accessibility, performance and security.

HTML questions show up in almost every front-end interview, from a junior web developer role to a senior engineer loop. Interviewers rarely want trivia. They want to hear that you understand why the markup matters: for accessibility, for search engines, for performance and for security.

This page collects 36 common questions, grouped by level and topic. Each answer is hidden: read the question, answer it out loud in your own words, then open it to compare. A good interview answer is short, correct and backed by a concrete example, and that is the style used here. A few questions ask you to read code and predict what happens; run those examples to check yourself.

Junior level

Fundamentals

1. What is HTML, and what is it not?

HTML (HyperText Markup Language) describes the structure and meaning of content: this is a heading, this is a list, this is a link. It is not a programming language: it has no variables or logic. Presentation belongs to CSS and behavior to JavaScript. Browsers follow the WHATWG HTML Living Standard, which is updated continuously rather than in numbered versions.

2. What is the difference between an element, a tag and an attribute?

A tag is the markup you type, like <p> or </p>. An element is the whole thing: start tag, content and end tag, which becomes a node in the DOM. An attribute is extra information in the start tag, such as href in <a href="/help">. See Elements and Attributes.

3. What does <!doctype html> do?

It tells the browser to render the page in standards mode. Without it, browsers fall back to "quirks mode", which imitates old browser bugs, for example in how box sizes and tables are calculated. It is not an HTML element and not a version number; it is the shortest string that switches standards mode on.

4. What are void elements?

Elements that cannot have content and therefore have no end tag: <img>, <br>, <hr>, <input>, <meta>, <link>, <source>, <track>, <wbr>, <area>, <col> and <embed>. A trailing slash (<br />) is allowed but does nothing in HTML. On non-void elements such as <div /> the slash is ignored, so the element stays open, which is a common bug.

5. What is the difference between block and inline elements?

Block-level elements such as <p>, <div> and <h2> start on a new line and take the full available width. Inline elements such as <a>, <em> and <span> flow inside a line of text and are only as wide as their content. Strictly speaking this is CSS behavior (display), which you can change; HTML defines content models instead. See Block and Inline Elements.

6. What is the difference between strong and b, or em and i?

<strong> means importance and <em> means stress emphasis that changes the meaning of a sentence. <b> and <i> carry no importance: <b> is for text you want to draw attention to (like keywords), <i> for an alternate voice, such as technical terms, foreign phrases or thoughts. They often look the same; the difference is meaning. See Text Formatting.

7. Why does every image need an alt attribute, and when should it be empty?

alt is the text alternative read by screen readers and shown when the image fails to load. It should convey what the image communicates in context. For purely decorative images, use an empty alt="" so assistive technology skips it. Leaving alt out entirely is wrong: some screen readers then read the file name.

8. What is the difference between id and class?

An id must be unique in the page and identifies one element: it is used for fragment links (#faq), <label for>, ARIA references and getElementById(). A class can be shared by many elements, and one element can have several classes; it is the usual hook for CSS. Prefer classes for styling, since id selectors have very high specificity.

9. What are semantic elements, and why do they matter?

Elements that describe their meaning: <header>, <nav>, <main>, <article>, <section>, <aside>, <footer>, plus <button>, <table>, <figure> and many more. They give assistive technology landmarks to navigate by, help search engines understand the page and make code easier to read. A <div> has no meaning at all. See Semantic Elements.

10. Absolute versus relative URLs?

An absolute URL includes the scheme and host (https://example.com/docs). A root-relative URL starts with / and is resolved against the current site (/docs). A document-relative URL such as ../img/logo.svg is resolved against the current file's location. Root-relative URLs are usually the safest choice inside a site. See File Paths.

11. How do you open a link in a new tab, and is it safe?

Use target="_blank". Modern browsers imply rel="noopener" for it, so the new page cannot reach your page through window.opener; adding rel="noopener" explicitly is still common for old browsers. Add noreferrer if you also want to hide the referring URL. Use new tabs sparingly and say so in the link text. See Link Targets.

12. What are HTML entities, and when do you need them?

Entities are codes for characters, like &lt; for <, &amp; for & and &nbsp; for a non-breaking space. You need them for characters that would otherwise be read as markup, mainly < and & in text and " inside double-quoted attributes. With UTF-8, you can type most other symbols directly. See HTML Entities.

Mid level

The document and scripts

13. What goes in the head, and which two meta tags should every page have?

The head holds metadata: the <title>, meta tags, stylesheets, scripts, icons and structured data. Every page needs <meta charset="utf-8"> (in the first 1024 bytes, so text decodes correctly) and <meta name="viewport" content="width=device-width, initial-scale=1"> (so mobile browsers don't render a zoomed-out desktop layout). See The Head Element.

14. What is the difference between defer, async and type="module"?

A plain <script src> stops HTML parsing while it downloads and runs. defer downloads in parallel and runs after parsing, in document order, just before DOMContentLoaded. async downloads in parallel and runs as soon as it arrives, in any order, which suits independent scripts like analytics. Module scripts are deferred by default and can use import. See Adding JavaScript.

The next question asks you to predict the order. Write down your guess, then run it.

Code reading: script timing
15. In the example above, why does B log before A, even though A comes first?

Module scripts, even inline ones, are deferred: they run once the whole document has been parsed. The classic script runs immediately when the parser reaches it. So the order is B, A, then DOMContentLoaded (which waits for deferred and module scripts), then load (which also waits for images, stylesheets and frames).

16. What is the DOM, and how is it different from the HTML source?

The Document Object Model is the live tree of objects the browser builds from your HTML, which JavaScript can read and change. It can differ from the source: the parser fixes errors and inserts missing elements (such as <tbody>), and scripts change it after load. DevTools' Elements panel shows the DOM; "View source" shows the original file. See The Document Object Model.

17. What are data-* attributes for?

They store your own custom data on an element, such as data-product-id="42", without inventing invalid attributes. JavaScript reads them through element.dataset.productId (dashes become camelCase), and CSS can select them with [data-state="open"]. Don't use them for content users need, and don't put secrets in them. See Custom Data Attributes.

Forms

18. Why must form controls have labels, and how do you connect them?

A label gives the control an accessible name that screen readers announce, and clicking it focuses or toggles the control, which makes small checkboxes easier to hit. Connect it with <label for="email"> matching the input's id, or by wrapping the input inside the <label>. A placeholder is not a substitute: it disappears as soon as you type. See Labels and Fieldsets.

19. When do you use GET and when POST for a form?

GET puts the data in the URL query string. Use it for searches and filters that are safe to repeat, bookmark and share. POST sends the data in the request body. Use it for anything that changes data on the server (sign-ups, orders, uploads) and for sensitive data that should not end up in URLs, history and logs. Uploads require method="post" with enctype="multipart/form-data". See Form Attributes.

20. How does built-in form validation work?

Attributes such as required, type="email", min/max, minlength and pattern define the rules. On submit, the browser checks every control, shows a message on the first invalid one and blocks the submission. CSS can style states with :invalid and :user-invalid, and JavaScript can add rules with setCustomValidity(). novalidate on the form turns the built-in checks off. Client-side validation is for user convenience; the server must always validate again. See Form Validation.

Read the next form carefully before you run it. Which of the four buttons submit the form?

Code reading: which buttons submit?
21. Why does a plain button inside a form submit it?

The default type of a <button> is submit. That's why "Save" submits, while "Preview" with type="button" does not. <input type="submit"> also submits, and a button outside the form can submit it through the form attribute, which points to the form's id. event.submitter tells you which control was used. Always write type="button" on buttons that only run JavaScript.

22. What is the difference between disabled and readonly?

Both stop the user from editing. A readonly field can still be focused and selected, and its value is submitted. A disabled control cannot be focused, is skipped by keyboard navigation and is not submitted. readonly only applies to text-like inputs and textareas; disabled works on all controls and on a whole <fieldset>.

Images and media

23. When do you use srcset and sizes, and when picture?

Use srcset with sizes when you have the same image at different resolutions and want the browser to pick the best file for the screen ("resolution switching"). Use <picture> with <source media> when you need different crops for different layouts ("art direction"), or <source type> to offer newer formats like AVIF with a fallback. See Responsive Images.

24. Why set width and height on images when CSS controls the size?

The browser uses the two attributes to compute the image's aspect ratio before it downloads, and reserves the right amount of space. Without them, content jumps when the image arrives, which hurts users and the Cumulative Layout Shift score. CSS such as max-width: 100%; height: auto still makes the image responsive.

25. Should every image use loading="lazy"?

No. Lazy loading delays images that are outside the viewport, which saves bandwidth for images further down the page. The main image at the top (often the Largest Contentful Paint element) should load eagerly, possibly with fetchpriority="high"; lazy-loading it makes the page feel slower. See HTML Performance.

Accessibility

26. What is ARIA, and what is the first rule of ARIA?

ARIA (Accessible Rich Internet Applications) is a set of attributes such as role, aria-label and aria-expanded that adjust what assistive technology is told about an element. The first rule: if a native HTML element or attribute does the job, use it instead. ARIA only changes what is announced; it adds no keyboard support or behavior, and wrong ARIA is worse than none. See ARIA.

27. How do you make a page usable with only a keyboard?

Use native interactive elements (<a href>, <button>, form controls), which are focusable and respond to Enter and Space. Keep the DOM order logical, keep the focus outline visible, never trap focus except in modal dialogs, and provide a skip link to the main content. tabindex="0" makes a custom widget focusable, tabindex="-1" makes an element focusable by script only, and positive values should be avoided because they break the natural order. See Keyboard and Focus.

Senior level

Parsing and rendering

Before reading question 28, predict what the browser builds from this invalid markup, then run it.

Code reading: how the parser repairs HTML
28. How does the HTML parser deal with invalid markup like the example above?

HTML parsing never fails: the spec defines exact error-recovery rules, so every browser builds the same DOM. A <div> cannot be inside a <p>, so the parser closes the paragraph before the <div>; the stray </p> then creates an extra empty paragraph. Missing </li> tags are implied by the next <li>, and a <tbody> is inserted into the table. That is why the console counts two paragraphs, and why a validator is still worth running. See HTML Validation.

29. Explain the critical rendering path and how HTML affects it.

The browser downloads the HTML, parses it into the DOM, builds the CSSOM from stylesheets, combines both into a render tree, then lays out and paints. Stylesheets in the head are render-blocking, and classic scripts are parser-blocking. You speed things up by keeping critical CSS small, using defer or modules for scripts, preloading key resources (<link rel="preload">), using fetchpriority for the main image, preconnecting to required origins and lazy-loading what is below the fold. See Resource Loading.

30. Which HTML features matter most for SEO?

A unique, descriptive <title> and meta description, one clear <h1> and a logical heading structure, descriptive link text, alt text, semantic landmarks, a <link rel="canonical"> to avoid duplicate content, hreflang alternates for translated pages, and structured data in JSON-LD for rich results. Fast, mobile-friendly pages matter too. Meta keywords are ignored by major search engines. See Meta Tags and Structured Data.

Security

31. How can HTML lead to cross-site scripting (XSS), and how do you prevent it?

XSS happens when untrusted input is inserted into a page as markup, so an attacker's <script> or onerror handler runs with your site's privileges. Prevent it by escaping output on the server (templating engines do this by default), using textContent instead of innerHTML in the browser, sanitizing HTML you truly must accept, and adding a Content Security Policy as a second line of defense. Never build href values from user input without rejecting javascript: URLs.

32. How do you embed untrusted content in an iframe safely?

Use the sandbox attribute, which by default blocks scripts, forms, popups, top-level navigation and gives the frame an opaque origin. Re-enable only what is needed, for example sandbox="allow-scripts". Never combine allow-scripts with allow-same-origin for content from your own origin, because the frame could then remove its own sandbox. Add referrerpolicy, allow (for permissions such as camera) and a title. See Iframes.

33. How can a page talk to a cross-origin iframe, and what is CORS?

The same-origin policy blocks reading another origin's DOM or responses. Windows exchange data with postMessage(data, targetOrigin), and the receiver must check event.origin against an exact allowlist. CORS is the separate mechanism by which a server lets other origins read its HTTP responses, using headers such as Access-Control-Allow-Origin, with an OPTIONS preflight for non-simple requests. See Cross-Document Messaging and CORS.

Architecture and modern HTML

34. What are web components?

Three standards used together: custom elements (customElements.define("price-tag", PriceTag) gives you your own tags with lifecycle callbacks), shadow DOM (an encapsulated subtree whose styles don't leak in or out) and <template>/<slot> (inert markup to clone and placeholders for the user's content). They work in any framework or none. Declarative shadow DOM (<template shadowrootmode="open">) even allows server rendering. See Templates and Web Components.

35. When do you use details, dialog or popover?

<details>/<summary> is for content that expands in place, such as FAQs (add a shared name for an exclusive accordion). <dialog> with showModal() is for a modal task that must be finished or dismissed, and it makes the rest of the page inert. The popover attribute is for non-modal overlays such as menus, tooltips and toasts, with light dismiss and top-layer rendering, often without any JavaScript. See Dialog and Popover.

36. What is progressive enhancement, and how does HTML support it?

Build a baseline that works with plain HTML (real links, real forms that submit to the server), then layer CSS and JavaScript on top for a better experience where they are available. HTML is designed for this: browsers ignore unknown elements and attributes, <details>, forms and validation work without scripts, and <picture>, <source> and <video> fall back gracefully. The result is more robust against failed script loads, slow networks and old devices.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which script attribute runs a script as soon as it has downloaded, in no guaranteed order?

    async scripts run whenever they arrive. defer and module scripts wait for parsing and keep document order.
  2. 2. What is the default type of a <button> inside a form?

    That's why buttons that only run JavaScript need an explicit type="button".
  3. 3. Which control's value is NOT included when its form is submitted?

    Disabled controls are skipped entirely. Readonly and hidden inputs are submitted normally.
  4. 4. What does the first rule of ARIA say?

    Native elements come with semantics, focus and keyboard behavior. ARIA only changes what assistive technology announces.

Summary

  • Junior questions test meaning: semantic elements, alt text, id vs class, links and entities.
  • Mid-level questions focus on how pages work: the head, script loading, the DOM, forms, responsive images and accessibility.
  • Senior questions go deeper into parsing, rendering performance, SEO, security (XSS, sandboxing, CORS) and modern platform features.
  • Answer with a short definition, a concrete example and the reason it matters. That structure works for every question here.

That's the end of the HTML course. You have the knowledge to build fast, accessible, standards-based pages, and the practice to prove it. Keep the HTML Cheat Sheet handy, and go build something.