HTML Interview Questions and Answers: 30 With Code Examples
HTML interview questions and answers are the first hurdle in most front-end interviews, and they are easier than candidates expect — provided you answer with reasons, not definitions. The questions are rarely about obscure tags. They are about judgement: why this tag and not that one, what breaks when an attribute is missing, and what you would change in a piece of real code. This guide gives you thirty of the questions that come up again and again, from beginner to advanced, each with a complete answer and a short code example you can run.
Interviewers rarely ask you to recite a specification. They ask you to explain a choice: why this tag and not that one, what breaks when an attribute is missing, and what you would do differently on a real page. The thirty questions in this guide are the ones that come up again and again in front-end interviews for junior and mid-level roles, grouped from beginner to advanced, each with a complete answer and a short code example you can run. Read them in order if you are preparing from zero; jump to the section that matches the role if you are short on time.
Every answer here is written the way a strong candidate would say it out loud: the direct answer first, then the reason behind it, then the detail that shows you have actually built pages — not just read about them. Where a question has a trap (and several do), the trap is named, so you do not walk into it.
Quick Takeaways
- HTML interview questions test judgement, not memory: the best answers explain why a tag or attribute exists, not just what it is called.
- Learn the semantic tags properly —
<header>,<nav>,<main>,<article>,<section>,<footer>— because half of all HTML interview questions are really about choosing the right one. - Every form question is secretly an accessibility question: labels, input types, and validation attributes are where beginners lose marks.
- Know the five void elements interviewers name most —
<img>,<br>,<hr>,<input>,<meta>— and that none of them takes a closing tag. - Deprecated tags (
<font>,<center>,<b>used for headings) are a favourite “what would you change in this code?” trap; the modern replacement is always CSS, not another tag. - Practise saying each answer out loud. An answer you can only recognise is not an answer you can give under pressure.
How to Use This Guide
Work through the questions in three passes. First pass: read the question, cover the answer, and say your version out loud before you look. Second pass: for every question you could not answer, type the code example into a file and open it in a browser — the act of running it fixes the idea in a way reading never does. Third pass: the night before the interview, re-read only the bold first line of each answer and the “watch out” notes. If you can reconstruct the rest from the first line, you are ready.
The questions are ordered the way interviews usually run: the interviewer starts easy, checks the fundamentals, then pushes into the places where beginners guess — forms, accessibility, and the newer HTML elements. Questions 1–10 are beginner level, 11–20 intermediate, and 21–30 advanced. A junior role rarely goes past question 20; a mid-level role will live in questions 15–30.
Beginner HTML Interview Questions
1. What is HTML and what does it do?
HTML — HyperText Markup Language — is the language that gives a web page its structure and meaning. It is not a programming language: it has no logic, no variables, and no loops. It is a markup language, which means it describes what the content is — this is a heading, this is a paragraph, this is a link — and the browser turns that description into the page you see.
Every web page you have ever opened is an HTML document at its core. CSS adds the presentation and JavaScript adds the behaviour, but without HTML there is nothing to style and nothing to interact with. That is why interviewers start here: if a candidate cannot explain what HTML is for, nothing built on top of it will be solid either.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>My First Page</title>
</head>
<body>
<h1>Hello, world</h1>
<p>This paragraph is HTML doing its job: marking content up so the browser — and a search engine, and a screen reader — can understand it.</p>
</body>
</html>
Watch out: “HTML is a programming language” is the single most common wrong first sentence in HTML interviews. Say “markup language” and explain the difference in one line — HTML describes content, it does not execute logic — and you have already separated yourself from candidates who memorised the acronym without understanding it.
2. What is the DOCTYPE declaration, and what happens if you leave it out?
The <!DOCTYPE html> declaration tells the browser which version of HTML the page uses, so it renders the page in standards mode instead of quirks mode. It is not an HTML tag — it is an instruction to the browser, and it must be the very first thing in the document, before even the <html> tag. There is nothing after it on the same line and no closing tag.
Leave it out, and the browser falls back to quirks mode, an old compatibility mode that emulates the buggy rendering of 1990s browsers. In quirks mode the box model changes, some CSS behaves differently, and the same page can look different in different browsers. Modern pages should never rely on quirks mode, and a missing DOCTYPE in an interview code sample is usually the first thing the interviewer points at.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Standards Mode Page</title>
</head>
<body>
<p>This page renders in standards mode because of the first line.</p>
</body>
</html>
Watch out: interviewers sometimes ask whether DOCTYPE is case-sensitive. It is not — <!doctype html> works — but the lowercase form is the convention, and the declaration must come first. A <html> tag before the DOCTYPE is a mistake, not a style choice.
3. What is the difference between an HTML element and an HTML tag?
A tag is the markup you type; an element is the whole thing the browser builds from it — the opening tag, the content, and the closing tag together. The tag is just the label in angle brackets. The element is the complete unit, and it is what the browser, the CSS, and JavaScript actually work with.
Take <p>This is a paragraph.</p>. The tags are <p> and </p>. The element is the entire line, content included. That distinction matters because CSS styles elements, JavaScript selects elements, and the document object model (DOM) is a tree of elements — tags do not exist in the DOM at all once the page is parsed.
<!-- Tags: <p> and </p>. Element: the whole line below. -->
<p>Tags are the brackets. The element is everything between them, plus the tags themselves.</p>
<!-- A void element has only one tag and no content: -->
<img src="photo.jpg" alt="A red bicycle leaning against a brick wall">
Watch out: candidates often use “tag” and “element” as if they were the same word. They are not, and interviewers notice. Say “element” when you mean the whole unit and “tag” when you mean the opening or closing marker, and your answers will sound precise without any extra effort.
4. What are HTML attributes, and how do they work?
Attributes are extra pieces of information you put inside an opening tag to modify an element — its behaviour, its identity, or extra data about it. Every attribute has a name and usually a value, written as name="value" inside the opening tag, separated from the tag name and from each other by spaces. The value is normally wrapped in double quotes.
Attributes fall into a few families. Some are global and work on almost every element — id, class, style, title, data-*. Some are specific to one element — src and alt on images, href on links, type on inputs. And some are boolean attributes, like required, disabled, or checked, which are switched on simply by being present; their value, if you give one, must be the attribute name itself or an empty string.
<!-- id and class identify the element; href and target control the link -->
<a href="https://allabouthtml.com/html-headings-hierarchy-seo/" id="headings-link" class="internal-link" target="_blank" rel="noopener">HTML headings guide</a>
<!-- required is a boolean attribute: its presence alone turns validation on -->
<input type="email" name="email" placeholder="you@example.com" required>
<!-- data-* attributes store custom data for JavaScript -->
<button type="button" data-question="3" data-difficulty="beginner">Next question</button>
Watch out: two classic mistakes. First, forgetting the quotes around an attribute value — browsers will often guess what you meant, but a value with a space in it breaks without quotes. Second, reusing the same id on two elements: an id must be unique in the document, while a class can be shared by as many elements as you like.
5. What is the difference between block-level and inline elements?
A block-level element starts on a new line and takes up the full width available to it; an inline element stays in the flow of the text and takes up only as much width as its content needs. That one difference drives most of how a page lays itself out before any CSS is applied.
Block-level elements include <div>, <p>, <h1>–<h6>, <ul>, <section>, and <article>. They stack vertically, and you can set their width, height, and vertical margins. Inline elements include <span>, <a>, <strong>, <em>, and <img> (technically a replaced inline element). They sit side by side inside a line of text, and setting a width or height on them has no effect unless you change their display type with CSS. A block element can contain inline elements and other block elements; an inline element should contain only text or other inline elements — never a block element.
<!-- Block elements stack: each one starts on a new line -->
<div>This div fills the full width.</div>
<p>This paragraph starts on a new line too.</p>
<!-- Inline elements share a line: -->
<p>An <a href="#">inline link</a> and a <strong>bold phrase</strong> sit inside the same line of text.</p>
Watch out: interviewers love the follow-up “can you put a <div> inside a <span>?” The answer is no — a <p> or a <span> containing a <div> is invalid HTML, and browsers will silently rearrange your markup to fix it, which produces bugs that are very hard to trace. Learn the rule and you will never debug that particular mystery.
6. What are void elements, and why do they have no closing tag?
Void elements are elements that cannot have any content, so they have no closing tag — a single tag is the whole element. The HTML standard defines a fixed list of them, and the ones interviewers name most are <img>, <br>, <hr>, <input>, <meta>, <link>, and <source>. Because there is nothing to put between an opening and a closing tag, the closing tag simply does not exist.
This is different from an element you choose to leave empty. A <div></div> with nothing inside is still a normal element with two tags; a <br> is a void element and writing </br> is an error. In HTML (unlike XHTML) you do not write a self-closing slash either — <br> is correct, <br /> is tolerated but unnecessary, and <br></br> is wrong.
<!-- Void elements: one tag each, no closing tag -->
<meta charset="UTF-8">
<link rel="stylesheet" href="styles.css">
<img src="diagram.svg" alt="Block and inline elements side by side">
<hr>
<label for="name">Your name</label>
<input type="text" id="name" name="name">
Watch out: the classic trap is <img>...</img> or <input></input> in a code sample the interviewer asks you to review. Spotting the invented closing tag is a quick win. The full void list is worth memorising: area, base, br, col, embed, hr, img, input, link, meta, param, source, track, wbr.
7. What is semantic HTML, and why should you use it?
Semantic HTML means choosing tags that describe the meaning of the content — <header>, <nav>, <main>, <article>, <footer> — instead of generic containers like <div> and <span> for everything. The word “semantic” means “relating to meaning”, and that is exactly what these tags add: the page tells the browser, the search engine, and the screen reader what each part is, not just how it looks.
It matters for three audiences. Screen readers use the landmarks to let users jump straight to the navigation or the main content instead of listening to the whole page. Search engines use the structure to understand which text is the article and which is a sidebar. And future developers — including you, six months later — can read the markup and understand the page without guessing what each <div> was for. None of that requires extra work: it is the same page, written with better tags.
<!-- Non-semantic: works, but says nothing about the content -->
<div class="header"><div class="nav">…</div></div>
<div class="content"><div class="post">…</div></div>
<div class="footer">…</div>
<!-- Semantic: the same page, and every part names itself -->
<header>
<nav aria-label="Main navigation">…</nav>
</header>
<main>
<article>…</article>
</main>
<footer>…</footer>
Watch out: interviewers often ask “is semantic HTML an SEO technique?” The honest answer is that it is primarily an accessibility and maintainability practice, and the SEO benefit is a side effect — search engines reward pages whose structure they can understand. Claiming it as a ranking trick oversells it.
8. What is the difference between <div> and <span>?
A <div> is a block-level generic container; a <span> is an inline generic container. That is the whole difference, and it follows from the block-versus-inline rule: a <div> starts on a new line and fills the available width, while a <span> sits inside a line of text and wraps only its content.
Both are meaningless on their own — they carry no semantic information, which is exactly why you reach for them when no semantic tag fits. Use a <div> to group large chunks of a page for layout or styling, and a <span> to mark a few words inside a sentence, for example to style one word differently or to give JavaScript a hook. Whenever a semantic tag fits — <section> for a group with a heading, <strong> for important text — use that instead.
<!-- div: a block container for a whole card -->
<div class="card">
<h2>Interview Prep</h2>
<p>Thirty questions, <span class="highlight">thirty answers</span>, one confident candidate.</p>
</div>
Watch out: the follow-up is usually “when would you use a <div> instead of a <section>?” The answer: when the grouping has no theme and no heading — a styling wrapper, a layout column, a JavaScript hook. If the group has a heading and a topic, it is a <section>; if it is just a box, it is a <div>.
9. How do HTML headings work, and why should a page have only one <h1>?
Headings from <h1> to <h6> create the outline of a page, like the chapters and sub-chapters of a book. <h1> is the page’s main title — there should be exactly one — and each level down is a subsection of the level above it. The order matters: an <h2> belongs under the <h1>, an <h3> under an <h2>, and you never skip a level (no <h1> straight to <h3>).
The outline is not decoration. Screen reader users navigate by headings the way sighted users scan a page, jumping from heading to heading to find the section they want; a broken hierarchy makes the page confusing to navigate. Search engines use headings to understand what the page is about, with the <h1> carrying the most weight. And the visual size of a heading is a side effect, not its purpose — choosing an <h4> because you like its size, when the content is really a top-level section, is one of the most common HTML mistakes in interviews.
<!-- A clean outline: one h1, sections in order, no skipped levels -->
<h1>HTML Interview Questions</h1>
<h2>Beginner Questions</h2>
<h3>What is HTML?</h3>
<h3>What is the DOCTYPE?</h3>
<h2>Intermediate Questions</h2>
<h3>What is the difference between article and section?</h3>
Watch out: “one <h1> per page” is the rule interviewers expect, and it is the right default. The nuance — that the HTML specification technically allows several <h1>s inside separate <article> elements — is worth knowing, but in practice one <h1> is what every style guide, every SEO checklist, and every screen reader user expects. Give the simple rule first, mention the nuance only if asked.
10. What is the difference between HTML and XHTML?
HTML is a markup language with forgiving rules; XHTML is HTML rewritten to follow the strict syntax rules of XML. In XHTML every element must be closed, every tag name must be lowercase, every attribute value must be quoted, and a single error can stop the whole page rendering. HTML tolerates mistakes — an unclosed paragraph, an unquoted value — and the browser recovers as best it can.
That strictness was XHTML’s selling point in the 2000s: a page that followed XML rules could be processed by any XML tool. In practice the strictness cost more than it saved — one typo could blank the page — and the web moved on. HTML5, the current standard, is not XML-based at all; it defines precise error recovery instead, so browsers handle sloppy markup consistently. XHTML still exists, but no new project should choose it, and interviewers ask the question mainly to check that you know the web’s history.
<!-- HTML5: forgiving, and this is all valid -->
<p>An unclosed paragraph still renders
<img src="logo.svg" alt="All About HTML logo">
<br>
<!-- XHTML: the same content, strict rules — everything closed, quoted, lowercase -->
<p>An unclosed paragraph still renders</p>
<img src="logo.svg" alt="All About HTML logo" />
<br />
Watch out: if the interviewer asks “which should I use for a new site?”, the answer is HTML5, without hesitation. The only reason to know XHTML today is to recognise it in legacy code — and to know that the self-closing slash (<br />) you still see in older codebases is an XHTML leftover, harmless in HTML5.
Intermediate HTML Interview Questions
11. What is the difference between <article> and <section>, and when do you use each?
Use <article> for content that makes sense on its own — it could be removed from the page and still be complete. Use <section> to group related content under a heading inside a larger whole. The test is simple: if the content would still make sense syndicated in a feed or printed alone, it is an article. If it only makes sense as part of the page it sits on, it is a section.
A blog post is an <article>. A product card in a listing is an <article>. A “Related articles” block, a chapter of a guide, or the “Ingredients” part of a recipe page is a <section>. Sections almost always have a heading; an article often has its own heading too, but the heading is not what makes it an article — its independence is.
<main>
<article>
<h1>Why Semantic HTML Matters</h1>
<p>This article stands alone: you could read it in a feed and miss nothing.</p>
<section>
<h2>Screen Readers</h2>
<p>This section only makes sense inside the article above it.</p>
</section>
<section>
<h2>Search Engines</h2>
<p>So does this one — it is a part of the whole, not a whole itself.</p>
</section>
</article>
</main>
Watch out: <section> is not a fancy <div>. A <div> is a meaningless container for styling; a <section> says “this is a thematic grouping of content” and belongs in the document outline. Wrapping a single button or a styling wrapper in a <section> is a common beginner mistake — if there is no heading and no theme, use a <div>.
12. How do you make an image accessible, and what makes good alt text?
Every meaningful image gets an alt attribute that describes the image’s content or function in words; decorative images get an empty alt="" so screen readers skip them. Alt text is read aloud by screen readers, shown when the image fails to load, and used by search engines to understand the image. It is one of the cheapest accessibility wins in HTML, and interviewers ask about it because so many developers leave it empty or fill it with file names.
Good alt text describes what the image shows or does, in the context of the page, without starting with “image of” — the screen reader already announces it is an image. A chart’s alt text should give the conclusion, not just say “chart”. A linked image’s alt text should say where the link goes, because the alt text becomes the link text. And an image that is pure decoration — a background flourish, a divider — gets alt="", which is not the same as no alt attribute at all: a missing alt makes the screen reader read out the file name instead.
<!-- Informative image: describe the content -->
<img src="bar-chart.svg" alt="Bar chart: HTML questions are 42% of front-end interview questions, CSS 31%, JavaScript 27%">
<!-- Linked image: describe the destination, not the picture -->
<a href="/html-projects/">
<img src="portfolio-thumb.jpg" alt="Open the HTML projects guide">
</a>
<!-- Decorative image: empty alt, so it is skipped -->
<img src="divider-flourish.svg" alt="" aria-hidden="true">
Watch out: the worst alt text is the file name — alt="IMG_4829.jpg" helps nobody. The second-worst is stuffing keywords into alt text for SEO; that is keyword stuffing, and search engines treat it as spam. Write for the person who cannot see the image, and the SEO benefit follows on its own.
13. What are srcset and sizes, and what problem does the <picture> element solve?
srcset lets the browser choose the right image file for the device — a small file for a small screen, a large one for a high-density display — and sizes tells the browser how wide the image will be displayed so it can choose before it downloads anything. Together they stop phones downloading desktop-sized images, which is one of the biggest and easiest performance wins on image-heavy pages.
The <picture> element solves a different problem: art direction. When you need a different image at different sizes — a wide landscape crop on desktop and a tight portrait crop on mobile — <picture> with <source> elements lets you swap the image entirely, not just its resolution. srcset changes the file; <picture> changes the picture.
<!-- srcset + sizes: same image, right file for the device -->
<img src="hero-800.jpg"
srcset="hero-400.jpg 400w, hero-800.jpg 800w, hero-1600.jpg 1600w"
sizes="(max-width: 600px) 400px, (max-width: 1200px) 800px, 1600px"
alt="A developer reviewing HTML interview questions on a laptop">
<!-- picture: a different crop on small screens (art direction) -->
<picture>
<source media="(max-width: 600px)" srcset="hero-portrait.jpg">
<source media="(max-width: 1200px)" srcset="hero-square.jpg">
<img src="hero-wide.jpg" alt="A developer reviewing HTML interview questions on a laptop">
</picture>
Watch out: a common confusion is thinking srcset and <picture> do the same job. If the interviewer asks “when would you use <picture> instead of srcset?”, the answer is: when the image itself must change — different crop, different composition, different format (such as WebP with a JPEG fallback) — not just a different size of the same image.
14. How does an HTML form work, and what is the difference between GET and POST?
A form collects input values and sends them to a URL named in its action attribute, using the method named in its method attribute. When the user submits, the browser gathers every named control in the form, encodes the values, and sends the request. Controls without a name attribute are not sent at all — a detail that causes more “my form sends nothing” bugs than any other.
GET appends the data to the URL as a query string (?q=html+forms). It is for safe, repeatable requests — searches, filters, anything you would happily bookmark or share. It has a practical length limit and must never carry passwords or sensitive data, because the values sit in the URL, the browser history, and the server logs. POST sends the data in the request body instead, so it stays out of the URL. It is for anything that changes something on the server — logins, sign-ups, orders, comments — and for large payloads such as file uploads, which need method="post" and enctype="multipart/form-data".
<!-- GET: a search — safe to bookmark, visible in the URL -->
<form action="/search" method="get">
<label for="q">Search the guides</label>
<input type="search" id="q" name="q">
<button type="submit">Search</button>
</form>
<!-- POST: a sign-up — data travels in the body, not the URL -->
<form action="/signup" method="post">
<label for="email">Email address</label>
<input type="email" id="email" name="email" required autocomplete="email">
<button type="submit">Create account</button>
</form>
Watch out: “GET is for getting data and POST is for sending data” is roughly right but too vague to impress. The sharp answer names the mechanism — URL query string versus request body — and the consequence: GET requests can be bookmarked, cached, and repeated safely, while POST requests change state and must not be repeated blindly (that is why browsers warn you about resubmitting a form).
15. Which input types did HTML5 add, and why do they matter?
HTML5 added semantic input types — email, url, tel, number, date, time, color, range, search, and others — that tell the browser what kind of data the field expects. The browser then does three useful things for free: it validates the value before submission, it shows the right keyboard on mobile (a numeric keypad for tel, an @ key for email), and it offers the right picker (a calendar for date, a slider for range).
That is the whole point, and it is what interviewers want to hear: choosing type="email" instead of type="text" is not cosmetic. It gives you free validation, better mobile keyboards, and better accessibility, with zero JavaScript. The same logic applies to attributes like required, min, max, pattern, and placeholder — each one moves work from your JavaScript into the browser, where it is faster and more consistent.
<form action="/book" method="post">
<label for="email">Email</label>
<input type="email" id="email" name="email" required>
<label for="date">Preferred date</label>
<input type="date" id="date" name="date" min="2026-11-19">
<label for="tickets">Tickets (1–6)</label>
<input type="number" id="tickets" name="tickets" min="1" max="6" value="2">
<label for="phone">Phone (optional)</label>
<input type="tel" id="phone" name="phone" autocomplete="tel">
<button type="submit">Book now</button>
</form>
Watch out: do not claim the browser validation is enough on its own. Client-side validation is a convenience for the user; it can always be bypassed, so the server must validate everything again. Saying that unprompted is the mark of a candidate who has shipped a real form.
16. How do you associate a <label> with an input, and why does it matter?
You link a label to its control in one of two ways: the for attribute matching the input’s id, or by wrapping the input inside the <label> element. The for/id pairing is the standard approach because it keeps the markup flexible — the label and the input can sit in different parts of the layout — while wrapping is shorter but ties the two together in the markup.
It matters because a label is not decoration. Clicking a label focuses its input, which makes small checkboxes and radio buttons far easier to use on touchscreens. Screen readers announce the label when the user reaches the field, so a form without labels is a form a blind user cannot complete — they hear “edit text, blank” instead of “Email address, edit text”. And the for/id link is exactly what automated accessibility checkers test for, so a missing label is one of the first things flagged in an audit.
<!-- Method 1: for/id — the standard approach -->
<label for="username">Username</label>
<input type="text" id="username" name="username" autocomplete="username">
<!-- Method 2: wrapping — the input is inside the label -->
<label>
<input type="checkbox" name="newsletter">
Send me the weekly HTML tips
</label>
Watch out: placeholder text is not a label. Placeholders disappear when the user starts typing, they are not read reliably by screen readers, and a form that uses placeholders instead of labels fails accessibility checks. The rule is simple: every input gets a real <label>, and a placeholder is only ever an extra hint.
17. What is the difference between <a href> and <link>?
<a> creates a clickable link in the visible page content; <link> loads a resource for the page itself and lives invisibly in the <head>. They share a family resemblance — both connect one resource to another — but they do opposite jobs, and confusing them is a reliable interview tell.
An <a href="..."> is content: the user sees it, clicks it, and navigates. A <link href="..."> is infrastructure: it tells the browser to fetch a stylesheet, a favicon, a font, or a preconnect hint before the page renders. A <link> never appears on the page, never takes a closing tag (it is a void element), and never belongs in the <body>.
<head>
<!-- link: invisible infrastructure — loads the stylesheet -->
<link rel="stylesheet" href="styles.css">
<link rel="icon" href="favicon.ico" sizes="any">
</head>
<body>
<!-- a: visible content — the user clicks it -->
<p>Read the <a href="/html-interview-questions-answers/">HTML interview questions guide</a> next.</p>
</body>
Watch out: interviewers sometimes ask “can you put a <link> in the <body>?” Technically the HTML specification allows <link> in the body in one case — itemprop microdata links — but for every practical purpose the answer is no: stylesheets, favicons, and preloads belong in the <head>, where the browser finds them before rendering starts.
18. What do target="_blank" and rel="noopener" do, and why do they belong together?
target="_blank" opens a link in a new tab; rel="noopener" stops the new page from reaching back into your page through window.opener. Used together, they give the user a new tab without handing the destination page a handle on the page they came from.
The risk without noopener is called reverse tabnabbing. The destination page can run window.opener.location = "https://fake-login.example.com", silently replacing your page in its original tab with a phishing copy while the user is looking at the new tab. The user switches back, sees a familiar-looking login page, and types their password into it. rel="noopener" closes that hole completely by setting window.opener to null in the new tab. Modern browsers now imply noopener for target="_blank" links, but writing it explicitly is still the expected practice — it protects users on older browsers and it shows the interviewer you know the attack exists.
<!-- Safe external link: new tab, no opener access -->
<a href="https://developer.mozilla.org/en-US/docs/Web/HTML" target="_blank" rel="noopener">MDN Web Docs</a>
<!-- Internal links do not need target="_blank" at all — let the user choose -->
<a href="/html-projects/">HTML projects guide</a>
Watch out: the common interview mistake is opening internal links in new tabs too. Users can open a new tab themselves whenever they want; forcing it on them breaks the back button’s expectations and annoys screen reader users. Reserve target="_blank" for links that genuinely leave your site, and always pair it with rel="noopener".
19. How do you embed video and audio in HTML?
Use the <video> and <audio> elements with one or more <source> elements inside, so the browser picks the first format it can play, plus fallback text for browsers that support neither. The elements give you built-in playback controls with the controls attribute, and attributes for autoplay, loop, muted, preload, and poster (the image shown before a video plays).
Two details interviewers always probe. First, autoplay: browsers block autoplay with sound, so a video that must autoplay needs muted as well — a muted autoplay is allowed, an audible one is not. Second, accessibility: a <video> should carry a <track> element with captions, because without captions the content is closed to deaf users and to everyone watching on mute.
<video controls width="640" poster="interview-poster.jpg" preload="metadata">
<source src="intro.mp4" type="video/mp4">
<source src="intro.webm" type="video/webm">
<track kind="captions" src="intro-en.vtt" srclang="en" label="English" default>
Your browser does not support the video element.
</video>
<audio controls>
<source src="episode.mp3" type="audio/mpeg">
<source src="episode.ogg" type="audio/ogg">
Your browser does not support the audio element.
</audio>
Watch out: never autoplay video with sound, and never set autoplay without muted and a good reason. It is the fastest way to fail a user-experience question, and interviewers treat it as a judgement test as much as a knowledge test: the candidate who volunteers “and I would never autoplay with sound” has understood the web, not just the tag.
20. What are data-* attributes, and when should you use them?
data-* attributes let you store custom, private data on an HTML element — any name you like after the data- prefix — so JavaScript can read it later without abusing other attributes. They are the official way to attach extra information to an element: the HTML specification reserves the data- prefix for exactly this, and the values are available in JavaScript through the element’s dataset property.
The classic uses are small and practical: a question number on a quiz button, a product id on an “add to cart” button, a difficulty level on a card. The rule is that data-* attributes are for data your scripts need, not for data the user should see (that belongs in visible content) and not for data a search engine should index (that belongs in structured data or real content). Stuffing visible information into data-* attributes where a real element would do is a misuse interviewers will call out.
<!-- data-* attributes carry the data; JavaScript reads them via dataset -->
<button type="button" class="answer-toggle" data-question="20" data-difficulty="intermediate">
Show answer
</button>
<script>
document.querySelector('.answer-toggle').addEventListener('click', (event) => {
const button = event.currentTarget;
console.log(button.dataset.question); // "20"
console.log(button.dataset.difficulty); // "intermediate"
});
</script>
Watch out: attribute names are lowercase and hyphenated in HTML (data-user-id), but JavaScript converts them to camelCase (dataset.userId). Forgetting that conversion — writing dataset.user-id, which is a syntax error — is a small slip that interviewers see often, so it is worth naming it yourself before they ask.
Advanced HTML Interview Questions
21. What are web components, and what is the Shadow DOM?
Web components are a set of browser-native technologies — custom elements, the Shadow DOM, and HTML templates — that let you build reusable, encapsulated components without a framework. A custom element lets you define your own tag, such as <user-card>, with its own behaviour; the Shadow DOM gives that component a private, sealed-off piece of the document tree so its styles and markup cannot leak out or be accidentally broken by the rest of the page; and the <template> element holds markup that is parsed but not rendered until you clone it into use.
The Shadow DOM is the idea interviewers press on. When you attach a shadow root to an element, the browser renders the shadow tree instead of the element’s normal children, and styles from the page cannot reach inside it (and its styles cannot leak out). That encapsulation is the whole reason component libraries use it — a date picker that looks the same on every site because no page’s CSS can touch its internals.
<template id="user-card-template">
<style>
.card { border: 1px solid #ccc; padding: 1rem; border-radius: 8px; }
h2 { margin: 0 0 0.5rem; font-size: 1.1rem; }
</style>
<div class="card">
<h2><slot name="name">Anonymous</slot></h2>
<p><slot name="role">No role given</slot></p>
</div>
</template>
<user-card>
<span slot="name">Aisha Khan</span>
<span slot="role">Front-end Developer</span>
</user-card>
<script>
class UserCard extends HTMLElement {
constructor() {
super();
const shadow = this.attachShadow({ mode: 'open' });
shadow.append(document.getElementById('user-card-template').content.cloneNode(true));
}
}
customElements.define('user-card', UserCard);
</script>
Watch out: interviewers often ask “why not just use a framework component?” The honest answer is that web components are framework-agnostic and native — the same <user-card> works in React, Vue, or plain HTML — but they are also lower-level: there is no built-in state management or templating engine, so frameworks still win for complex applications. Saying both halves shows judgement rather than enthusiasm for one tool.
22. What are the <dialog> and popover features, and when would you use them?
The <dialog> element is the native way to build a modal dialog, and the popover API is the native way to build lightweight popups, menus, and tooltips — both without JavaScript libraries. A <dialog> opened with showModal() gets a top layer, a backdrop, focus trapping, and Escape-to-close behaviour for free. A popover, created with the popover attribute and triggered by popovertarget, gets the same top-layer behaviour for smaller floating UI.
The difference is scope. A modal dialog interrupts the user — a confirmation, a login prompt, a form that must be completed before continuing. A popover does not interrupt — a tooltip, a “more options” menu, a help hint that the user can dismiss by clicking elsewhere. Interviewers ask this pair together because beginners reach for JavaScript libraries for both jobs, when the browser has shipped native answers since 2023.
<!-- A modal dialog: interrupts, traps focus, Escape closes it -->
<dialog id="confirm-dialog">
<h2>Delete this draft?</h2>
<p>This cannot be undone.</p>
<form method="dialog">
<button value="cancel">Cancel</button>
<button value="delete">Delete</button>
</form>
</dialog>
<button onclick="document.getElementById('confirm-dialog').showModal()">Delete draft</button>
<!-- A popover: lightweight, dismissible, no interruption -->
<button popovertarget="help-popover">What is semantic HTML?</button>
<div id="help-popover" popover>
<p>Semantic HTML uses tags that describe meaning — header, nav, main, article — instead of generic divs.</p>
</div>
Watch out: showModal() and show() are different methods — show() opens a dialog without the top layer, backdrop, or focus trap, which is almost never what you want for a modal. And a popover is not a replacement for a dialog: if the user must answer before continuing, use <dialog>; if they can ignore it, use a popover.
23. How does a browser turn HTML into a page?
The browser parses the HTML into a DOM tree, fetches and parses the CSS into a CSSOM tree, combines them into a render tree, lays the tree out, and paints it to the screen. That five-step pipeline — parse, style, layout, paint, and then composite — is the answer interviewers expect, and each step is a place where a follow-up question can land.
The details worth knowing: parsing happens incrementally, so the browser can start rendering before the whole document arrives. A <script> without defer or async blocks parsing while it downloads and runs, which is why scripts belong at the end of the body or carry defer. A stylesheet blocks rendering until it loads, which is why CSS belongs in the <head>. And when JavaScript changes the DOM, the browser repeats layout and paint for the affected parts — the reason frameworks batch their updates.
<!-- defer: download in parallel, run after parsing, in order -->
<script src="app.js" defer></script>
<!-- async: download in parallel, run as soon as it arrives -->
<script src="analytics.js" async></script>
Watch out: the common trap is saying “the browser reads the HTML top to bottom and shows it”. That is true but shallow. The interviewer wants the pipeline vocabulary — DOM, CSSOM, render tree, layout, paint — because those words are the handles for every performance question that follows. Learn the five steps in order and you can answer any of them.
24. Which meta tags matter most, and what do they do?
The essential meta tags are charset, viewport, description, and the Open Graph/Twitter Card tags — and each one serves a different audience. charset="UTF-8" tells the browser how to decode the text; without it, non-English characters can render as garbage. viewport tells mobile browsers the page is responsive and how to scale it. description is the text search engines show under your title in results. Open Graph tags (og:title, og:description, og:image) control how the page looks when shared on social media.
Beyond those, robots controls search engine indexing, theme-color colours the browser chrome on mobile, and author names the page’s author. What matters in an interview is not listing every tag — it is naming the four essential ones and saying who each one is for: the browser, the mobile viewport, the search result, and the social share.
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Thirty HTML interview questions with complete answers and runnable code examples.">
<meta name="robots" content="index, follow">
<meta name="theme-color" content="#c0392b">
<meta property="og:title" content="HTML Interview Questions and Answers: 30 With Code Examples">
<meta property="og:description" content="Thirty HTML interview questions with complete answers and runnable code examples.">
<meta property="og:image" content="https://allabouthtml.com/images/html-interview-questions.jpg">
<meta property="og:type" content="article">
<title>HTML Interview Questions and Answers: 30 With Code Examples</title>
</head>
Watch out: the keywords meta tag (<meta name="keywords" content="...">) is dead — search engines ignored it years ago because it was abused for stuffing. Naming it as important marks you as someone who learned SEO from a decade-old tutorial. The description tag is the one that still earns its place.
25. What is ARIA, and when should you NOT use it?
ARIA — Accessible Rich Internet Applications — is a set of attributes that add accessibility information HTML cannot express on its own, such as the role of a custom widget or the live state of a dynamic region. role, aria-label, aria-expanded, aria-live, and aria-hidden are the ones you will meet most. ARIA exists for the cases where native HTML has no element for the job — a tab panel, a custom slider, a toast notification.
The rule interviewers want to hear is the first rule of ARIA: do not use ARIA if a native HTML element can do the job. A real <button> is better than a <div role="button"> because the button already has keyboard support, focus behaviour, and screen reader announcements built in — the ARIA version recreates all of that by hand and usually gets some of it wrong. ARIA is a patch for the gaps, not a substitute for semantic HTML. And ARIA never changes behaviour or appearance; it only changes what assistive technology announces, so a wrong aria-label can make a page less accessible than no label at all.
<!-- Wrong: a div pretending to be a button, patched with ARIA -->
<div role="button" tabindex="0" aria-label="Submit form">Submit</div>
<!-- Right: a real button — keyboard, focus, and announcements built in -->
<button type="submit">Submit</button>
<!-- Right use of ARIA: a custom tab widget HTML has no element for -->
<div role="tablist" aria-label="Interview sections">
<button role="tab" aria-selected="true" aria-controls="panel-basics" id="tab-basics">Beginner</button>
<button role="tab" aria-selected="false" aria-controls="panel-advanced" id="tab-advanced">Advanced</button>
</div>
Watch out: the interview trap is “add ARIA to make this accessible” applied to a page that just needs semantic tags. The correct first move is almost always native HTML — a <nav> instead of role="navigation", a <button> instead of role="button", a <label> instead of aria-label on an input. ARIA is the last resort, not the first tool.
26. How do you lazy-load images, and why?
Add loading="lazy" to an <img> or <iframe> and the browser defers downloading it until it is close to entering the viewport. The page loads faster, uses less data, and the user never waits for images they never scroll to. It is a single attribute, it works in all modern browsers, and it is the easiest performance optimisation in HTML.
Two details matter. First, lazy-load only below-the-fold images — the hero image at the top of the page should load eagerly, or the user stares at a blank space while the largest element on the page arrives late. Second, reserve the image’s space with width and height attributes (or CSS aspect-ratio) so the page does not jump when the lazy image finally loads; that layout shift is exactly what the Cumulative Layout Shift metric penalises.
<!-- Eager: the hero image, needed immediately -->
<img src="hero-800.jpg" alt="Interview preparation notes on a desk" width="800" height="450" fetchpriority="high">
<!-- Lazy: below the fold, loaded only when scrolled toward -->
<img src="diagram-800.jpg" alt="DOM tree diagram" width="800" height="450" loading="lazy">
Watch out: loading="lazy" on an image that is already visible on load is a mistake, not an optimisation — it delays the most important image on the page. The interviewer is testing whether you know where to apply the technique, not just that the attribute exists.
27. What are resource hints — preload, prefetch, and preconnect?
Resource hints are <link> tags that tell the browser about work it will need soon, so it can start early: preload fetches a critical resource now, prefetch fetches a likely-next-page resource when idle, and preconnect opens the connection to another origin ahead of time. They are hints, not commands — the browser may ignore them — but used sparingly they remove real delays from page loads.
Each one has a distinct job. preload is for something the current page needs urgently and the browser would otherwise discover late — a web font, the hero image, a critical stylesheet. prefetch is for the next navigation — the page the user will probably click to next — fetched quietly while the browser is idle. preconnect is for third-party origins: opening a connection to a font host or an analytics domain early saves a DNS lookup, a TCP handshake, and a TLS negotiation when the resource is actually requested. And dns-prefetch is the lighter version that only resolves the domain name.
<head>
<!-- Preload the font the hero text needs right now -->
<link rel="preload" href="fonts/inter.woff2" as="font" type="font/woff2" crossorigin>
<!-- Preconnect to the font host before any request goes there -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<!-- Prefetch the guide the reader will probably open next -->
<link rel="prefetch" href="/html-projects/">
</head>
Watch out: overusing preload is worse than not using it — every preloaded resource competes with the resources the browser already knows it needs, and preloading something the page never uses wastes bandwidth outright. The interview answer is restraint: preload one or two critical resources, preconnect to one or two origins, and prefetch only the next page you are confident about.
28. Which HTML tags are deprecated, and what should you use instead?
Deprecated tags are tags the HTML standard has retired because CSS or a better element does the job — and the ones interviewers name most are <font>, <center>, <b> used as a heading, <u> used for emphasis, <marquee>, <blink>, and <frame>/<frameset>. They still render in browsers for backwards compatibility, but they should never appear in new code, and spotting them in a code sample is a standard interview exercise.
The replacement is always the same pattern: presentation moves to CSS, structure moves to a semantic element. <font color="red"> becomes a CSS class. <center> becomes text-align: center or a flexbox layout. <b> for a heading becomes a real heading tag. <frameset> — the old way to split a page into separate documents — becomes separate pages, an <iframe>, or a single-page layout. And <marquee> and <blink> have no replacement at all, because moving, blinking text is an accessibility failure, not a feature.
<!-- Deprecated: presentation baked into the markup -->
<center><font color="red" size="5">Welcome to my page</font></center>
<b>Chapter One</b>
<!-- Modern: structure in HTML, presentation in CSS -->
<h1 class="page-title">Welcome to my page</h1>
<h2>Chapter One</h2>
.page-title {
text-align: center;
color: #c0392b;
font-size: 2rem;
}
Watch out: <b> and <i> are not deprecated — that is the trap. They still exist, but their meaning changed: <b> now means “bring attention to this text” without implying importance (use <strong> for importance), and <i> means text in an alternate voice, such as a technical term or a phrase in another language (use <em> for emphasis). The deprecated list is about <font>, <center>, <marquee>, and friends — do not throw <b> and <i> out with them.
29. How do you validate HTML, and why does it matter?
You validate HTML by running it through the W3C Markup Validation Service — validator.w3.org — which checks the document against the HTML specification and lists every error and warning. You paste a URL, upload a file, or paste the markup directly, and the validator reports problems like unclosed tags, duplicate ids, invalid nesting, and unknown attributes, with line numbers for each one.
It matters because browsers are forgiving: an invalid page usually still renders, so errors hide. A missing closing tag can silently swallow the rest of a page’s content into the wrong element; a duplicate id can make JavaScript target the wrong node; an <a> wrapped around a <div> in the wrong context can break in one browser and work in another. Validation catches those errors before your users do, and a clean validation report is a fast way to prove a page’s markup is sound — which is why interviewers ask about it, and why a “validate early, validate often” habit is worth stating out loud.
<!-- A page that looks fine but fails validation: -->
<!-- 1. A div inside a paragraph — invalid nesting -->
<p>This paragraph contains a <div>block element</div> inside it.</p>
<!-- 2. The same id twice — ids must be unique -->
<input type="text" id="email" name="email">
<input type="text" id="email" name="email-confirm">
<!-- 3. An img with no alt — an error in strict validation -->
<img src="logo.svg">
Watch out: validation is a tool, not a grade. Some warnings are harmless — a validator warning about a proprietary attribute on an embedded widget does not mean the page is broken — and a perfectly valid page can still be inaccessible or badly designed. The strong answer is “validate to catch the errors browsers hide, then judge the warnings by whether they affect real users”.
30. What is the <canvas> element, and how is it different from SVG?
<canvas> is a blank drawing surface that JavaScript paints on pixel by pixel; SVG is a set of markup elements that describe shapes as objects in the DOM. That one difference decides everything else. A canvas is a bitmap: once you draw a circle, the browser forgets it was a circle — it is just pixels, and changing it means redrawing the whole scene. SVG is vector and structural: every shape is an element you can style with CSS, attach events to, and inspect in the developer tools.
Choose canvas when you need many fast-changing pixels — games, particle effects, image manipulation, charts redrawn sixty times a second. Choose SVG when you need crisp graphics at any size, accessible shapes, or individual elements you can interact with — icons, logos, diagrams, data visualisations with hover states. Interviewers ask this because it tests whether you pick tools by their properties rather than by habit.
<!-- Canvas: JavaScript draws pixels; the circle is not an element -->
<canvas id="game" width="400" height="200"></canvas>
<script>
const ctx = document.getElementById('game').getContext('2d');
ctx.fillStyle = '#c0392b';
ctx.beginPath();
ctx.arc(200, 100, 60, 0, Math.PI * 2);
ctx.fill();
</script>
<!-- SVG: the circle IS an element — styleable, scriptable, accessible -->
<svg width="400" height="200" role="img" aria-label="A red circle">
<circle cx="200" cy="100" r="60" fill="#c0392b"></circle>
</svg>
Watch out: a <canvas> with no fallback content is invisible to screen readers — the drawing is pixels, and assistive technology sees an empty box. If the canvas content matters, add a text alternative: fallback content inside the <canvas> element, an aria-label, or a visually hidden description. SVG, by contrast, can carry a <title> and a <desc> element, which is one more reason to prefer it for diagrams and charts.
Block vs Inline, Div vs Span, Canvas vs SVG — At a Glance
| Comparison | First option | Second option | Remember it as |
|---|---|---|---|
| Block vs inline | Block: new line, full width (div, p, h1) | Inline: shares a line, content width (span, a, strong) | Blocks stack, inlines flow |
<div> vs <span> | Block-level generic container | Inline generic container | Same job, different display |
<article> vs <section> | Stands alone (blog post, product card) | Part of a larger whole (a chapter, a tab) | Article survives alone |
<b> vs <strong> | Visual attention, no importance | Importance, announced by screen readers | Strong means something |
<i> vs <em> | Alternate voice (term, foreign phrase) | Emphasis, changes the meaning | Emphasis changes meaning |
| GET vs POST | Data in the URL, bookmarkable | Data in the body, changes state | GET reads, POST writes |
<canvas> vs SVG | Pixels, redrawn by JavaScript | Elements in the DOM, styled by CSS | Canvas paints, SVG describes |
<dialog> vs popover | Interrupts — must be answered | Does not interrupt — dismissible | Dialog blocks, popover hints |
srcset vs <picture> | Same image, right file size | Different image per screen | srcset sizes, picture swaps |
| Native element vs ARIA | Real <button>, <nav>, <label> | role="button" on a <div> | Native first, ARIA last |
Mistakes That Cost Marks in HTML Interviews
The questions above cover the knowledge. These are the habits that decide whether the interviewer trusts it.
Answering with a definition instead of a reason. “Semantic HTML uses meaningful tags” is a definition; “semantic HTML lets a screen reader user jump to the main content, and it is the reason my pages pass accessibility audits” is an answer. Give the reason first, the definition second.
Choosing a tag by how it looks. Picking <h4> because you like its size, or <b> because you want bold text, tells the interviewer you think of HTML as a styling language. It is a structure language. Size and boldness are CSS decisions; the tag is a meaning decision.
Forgetting the label. In live coding exercises, the form without labels is the most common failure in the room — and the easiest to avoid. Label every input, even in a five-minute exercise, and the interviewer notices.
Treating validation as optional. “It renders fine” is not an answer to a validation question. Browsers hide invalid markup; the validator finds it. Say you validate, and mean it.
Overusing ARIA. Reaching for role="button" before reaching for <button> is the clearest signal of a developer who learned accessibility from a checklist instead of from HTML itself. Native elements first, ARIA only where no native element exists.
Frequently Asked Questions
1. How many HTML interview questions should I prepare for a junior front-end role?
Prepare the twenty beginner and intermediate questions in this guide first — they cover the ground a junior interview actually tests: document structure, semantic tags, forms, links, images, and accessibility basics. The advanced ten are your safety net for a second-round or mid-level interview. Quality beats quantity: ten answers you can say out loud beat thirty you can only recognise.
2. Do interviewers still ask HTML questions when frameworks dominate front-end jobs?
Yes — and often first. Frameworks change every few years; the HTML underneath them does not. An interviewer who asks about semantic tags, form labels, and the DOM is checking whether you understand the platform your framework runs on. Candidates who know React but not HTML are the ones who build inaccessible components and cannot debug a layout bug that turns out to be invalid nesting.
3. Should I memorise the full list of void elements for an interview?
Know the common five — img, br, hr, input, meta — and know that the full list is fixed by the specification (area, base, br, col, embed, hr, img, input, link, meta, param, source, track, wbr). Nobody expects you to recite all fourteen under pressure, but naming the common ones and knowing that the list exists shows the right kind of preparation.
4. What is the best way to practise HTML interview questions?
Type the code, do not just read it. For each question in this guide, open a blank file, write the example from memory, and open it in a browser. Then break it on purpose — remove the DOCTYPE, nest a div inside a span, delete a label — and watch what happens. The bugs you have seen with your own eyes are the ones you will recognise in an interview code sample.
5. What should I learn after HTML for front-end interviews?
CSS next, in this order: the box model, flexbox, grid, and responsive design with media queries — then JavaScript fundamentals: the DOM, events, and fetch. The interview arc is always the same: HTML proves you can structure content, CSS proves you can present it, and JavaScript proves you can make it respond. Each layer is only as strong as the one underneath it.
Conclusion
Thirty questions is a lot to prepare, but the pattern behind them is simple: HTML interviews test whether you choose tags for their meaning, whether you think about the people who use your pages — including the ones who cannot see them — and whether you know what the browser does with your markup after you write it. The candidates who do well are not the ones who memorised the most tags. They are the ones who can explain, for any tag, why it exists and what breaks when it is missing.
Work through this guide out loud, type every example, and break a few pages on purpose. Then walk into the interview knowing that the fundamentals — one <h1>, labelled forms, semantic landmarks, valid markup — are already yours. The framework questions will take care of themselves; the HTML questions are the ones that decide whether you get to answer them.
Related Articles You’ll Love
- HTML Headings H1 to H6: Hierarchy, SEO Rules, and Common Mistakes — the heading rules behind question 9: one H1, sections in order, and the mistakes that break a page outline.
- 10 HTML Projects for Beginners That Actually Teach You — the fastest way to practise these answers: ten complete pages that use the semantic tags, forms, and media elements this guide tests.
- HTML Accessibility Checklist: Landmarks, ARIA, and Keyboard Navigation — the full checklist behind questions 7, 12, 16, and 25: landmarks, labels, focus order, and when ARIA is the wrong tool.
- Debugging HTML: W3C Validator Errors and How to Fix Them — the validator workflow from question 29, with the common errors explained and fixed one by one.
- rel noopener Explained: HTML Security Attributes Guide — the security attributes behind question 18: why target=”_blank” without rel=”noopener” is a real vulnerability, not a style choice.