HTML Interview Questions & Answers
Curated HTML interview questions with detailed answers, grouped by topic. Search, revise and get interview-ready.
HTML Introduction
HTML stands for HyperText Markup Language. It is used to structure content on the web — headings, paragraphs, links, images, and forms — so browsers know what to display and how.
No. HTML is a markup language, not a programming language — it has no variables, loops, or conditional logic. It only describes structure and meaning; logic comes from JavaScript.
The DOM (Document Object Model) is the tree-like structure a browser builds in memory after parsing an HTML document. JavaScript interacts with the page by reading and modifying this DOM, not the raw HTML text.
HTML provides structure and content, CSS controls presentation and layout, and JavaScript adds behavior and interactivity. They are separate layers that combine to build a complete web page.
HTML Setup
Just a text editor and a web browser. No compiler, build tool, or server is required to write and view a basic HTML page.
.html (or the older .htm), which tells the operating system and browser to render the file as a web page.
Web servers are configured to automatically serve a file named index.html when a directory URL is requested without a specific filename, making it the default entry point.
HTML Document Structure
It tells the browser to render the page using the HTML5 standards mode, avoiding inconsistent "quirks mode" rendering used for very old, non-standard documents.
<head> contains metadata not shown directly on the page (title, stylesheets, meta tags), while <body> contains everything the user actually sees and interacts with.
It declares the character encoding early so the browser interprets all subsequent text — including special characters and emoji — correctly before rendering begins.
Exactly one of each. Having more than one of any of these elements produces invalid HTML and can lead to unpredictable rendering.
HTML Attributes
An attribute provides extra information about an element, written as name="value" pairs inside the element’s opening tag, e.g. <a href="...">.
A boolean attribute takes no value — its mere presence enables a feature. Examples include disabled, required, and checked.
class can be applied to many elements and reused for shared styling, while id must be unique within the page and is typically used for a single, specific target like a same-page anchor or JavaScript hook.
Unquoted values break as soon as they contain a space or special character. Quoting (single or double) keeps the value unambiguous and is considered best practice even when technically optional.
Headings & Paragraphs
Six, from <h1> (most important) to <h6> (least important), used to build a logical outline of the page content.
Typically exactly one, representing the main topic of the page — similar to a book’s title — with subsequent sections using <h2> and deeper levels.
Heading levels should reflect document structure, not visual appearance. Skipping levels for styling purposes breaks the logical outline that screen readers rely on for navigation — use CSS for styling instead.
Text Formatting
<strong> and <em> carry semantic meaning (importance and emphasis) that screen readers announce differently, while <b> and <i> are purely visual with no added meaning.
<br> forces a single line break within a block of text. It should not be used to create space between paragraphs — separate <p> elements or CSS margin are the correct tools for that.
<sub> renders subscript text (like the 2 in H2O) and <sup> renders superscript text (like the 10 in 2^10), both shifting the text’s baseline and typically reducing its size.
HTML Links
An absolute URL includes the full address (protocol and domain), like https://example.com/about. A relative URL points to a location relative to the current page, like about.html or /blog/post-1.
Without it, the new page opened in the tab can access the original page through window.opener, which is a security and performance risk. rel="noopener noreferrer" prevents that access.
Using a fragment identifier — a hash followed by the target element’s id, e.g. <a href="#contact">, linking to an element like <h2 id="contact">.
Screen reader users often navigate by jumping between links out of context, so vague text like "click here" gives them no information about the destination. Descriptive link text is far more accessible.
HTML Images
It provides a text alternative for the image — read aloud by screen readers, shown if the image fails to load, and used by search engines to understand the image content.
An empty string, alt="", so screen readers skip over it entirely instead of reading out an unhelpful file name for an image that carries no meaning.
It lets the browser reserve the correct space for the image before it finishes loading, preventing surrounding content from jumping around (layout shift) as the page renders.
It tells the browser to defer loading that image until it is close to entering the viewport, improving initial page load performance for pages with many offscreen images.
HTML Lists
<ul> creates an unordered (bulleted) list for items with no particular sequence, while <ol> creates an ordered (numbered) list for sequential items.
A <ul> or <ol> element. <li> elements placed directly inside anything else are invalid HTML.
A <dl> pairs terms (<dt>) with their definitions (<dd>) — useful for glossaries, metadata, or key-value style content.
Div & Span
<div> is a block-level generic container, starting on a new line and taking full width. <span> is an inline generic container, flowing with surrounding text and only as wide as its content.
Semantic elements like <header>, <nav>, and <article> describe their content’s role, improving accessibility and SEO, whereas <div> carries no meaning at all — it should be a fallback, not a default.
A term for markup that overuses <div> for everything, making the structure harder to read, style, and understand for both developers and assistive technology.
HTML Tables
<th> defines a header cell (bold and centered by default, with semantic meaning for assistive technology), while <td> defines a standard data cell.
colspan merges a cell across multiple columns, and rowspan merges a cell across multiple rows, letting a single cell visually span a larger area of the table.
Using tables for layout (common in the early 2000s) hurts accessibility, since screen readers announce genuine tabular relationships that don’t exist, and it hurts responsiveness. CSS Grid or Flexbox should be used for layout instead.
It tells assistive technology whether a header applies to a column ("col") or a row ("row"), which is especially important for complex tables with multiple header levels.
HTML Forms
action specifies the URL the form data is submitted to, and method specifies how — "get" appends data to the URL, "post" sends it in the request body.
By matching the label’s for attribute to the input’s id. This makes the input clickable via its label text and is essential for screen reader accessibility.
Placeholder text disappears once the user starts typing and is not reliably announced by all screen readers, so relying on it alone leaves the field effectively unlabeled for many users.
<fieldset> groups related form controls together (like a set of radio buttons), and <legend> provides a caption describing that group.
Input Types
Specific types like email, tel, and number trigger the most appropriate mobile keyboard and provide free client-side validation, improving usability without any extra code.
By giving them the same name attribute — the browser then treats them as a mutually exclusive group, regardless of how many there are.
Checkboxes allow any number of independent selections, while radio buttons restrict the user to exactly one selection per group (same name attribute).
It restricts which file types are shown/selectable in the file picker, e.g. accept="image/png, image/jpeg" limits selection to those image formats.
Form Validation
It prevents the form from submitting until that field has a value, using the browser’s built-in constraint validation with no JavaScript needed.
It requires the input’s value to match a given regular expression before the form can submit, useful for formats like ZIP codes that a specific input type doesn’t cover.
Native validation can be bypassed (e.g. via dev tools or a direct request), so the server must always validate and sanitize incoming data again before trusting it.
Semantic HTML
Semantic elements (like <header>, <nav>, <main>, <article>) describe their meaning and role, unlike generic <div>. This helps screen readers, search engines, and other developers understand the page structure.
<article> is for content that could stand alone, like a blog post. <section> is for a thematic grouping within a page, usually accompanied by its own heading.
Exactly one, representing the page’s primary, unique content — excluding repeated elements like headers, footers, and navigation.
It provides a caption for a <figure>, such as an image, diagram, or code block, describing what it shows.
Block vs Inline Elements
A block-level element starts on a new line and takes up the full available width by default; an inline element flows with surrounding content and only takes as much width as needed.
Yes — the CSS display property (block, inline, inline-block, flex, grid, none) can change how any element behaves, regardless of its default.
Unlike text-based inline elements, <img> is a "replaced" element and accepts width and height even though it is inline-level by default.
Classes & IDs
class can be reused across many elements for shared styling, while id must be unique across the entire page.
A duplicate id can cause CSS to apply inconsistently and breaks JavaScript methods like document.getElementById() that expect exactly one match.
Yes, classes are space-separated in the class attribute, e.g. class="btn btn-primary btn-large", letting you compose small, reusable style rules.
HTML Entities
Those characters have special meaning — they define tags. To display them as literal text, you must use entities like < and > instead.
A way to represent any Unicode character by its code point, like © or © for the copyright symbol, as an alternative to named entities.
Failing to escape characters like < and & in content coming from users can allow malicious markup or scripts to be injected into the page — a cross-site scripting (XSS) vulnerability.
Head Elements
It controls how a page scales on mobile devices. Without it, mobile browsers render the page at a wide desktop width and zoom out, breaking responsive layouts.
<style> embeds CSS rules directly inline in the document, while <link rel="stylesheet"> loads CSS from a separate, cacheable file.
It delays execution of the script until after the HTML has finished parsing, while still preserving the order scripts appear in — commonly used for scripts that need the full DOM.
IFrames
It embeds another HTML document inside the current page, rendered in its own independent browsing context — commonly used for maps, videos, and third-party widgets.
It applies restrictions to the embedded content, such as disabling scripts or form submission, as a security measure when embedding untrusted content.
It gives screen reader users an accessible name describing the embedded content before they enter it — without one, the iframe is announced with no useful context.
Audio & Video
It shows the browser’s built-in play/pause/volume UI, letting users control playback without any custom JavaScript.
Different browsers support different video formats. Multiple sources let the browser pick the first format it supports, providing broader compatibility.
Captions or subtitles, loaded from a WebVTT file, improving accessibility for deaf and hard-of-hearing users.
Browsers restrict autoplaying audio/video with sound to avoid disrupting users unexpectedly. Autoplay generally only works reliably when the media is also muted.
Data Attributes
It stores custom data directly on an HTML element, without inventing new HTML attributes, for use by CSS attribute selectors or JavaScript.
Through the element’s dataset property, e.g. element.dataset.userId, which automatically converts kebab-case attribute names to camelCase.
No — data attributes are visible in the page source and can be read or modified by anyone using browser dev tools.
SVG Basics
Scalable Vector Graphics — an XML-based format for drawing 2D graphics with shapes and paths instead of pixels, so it stays crisp at any zoom level or resolution.
It defines the internal coordinate system of the SVG canvas independently of its displayed width/height, which is what allows the graphic to scale cleanly.
Inline SVG can be styled with CSS (fill, stroke) and manipulated or animated with JavaScript, while an <img>-referenced SVG is treated as an opaque image.
HTML Accessibility
Using the correct semantic element for the job. Native elements like <button>, <a>, and <nav> come with built-in keyboard support and screen reader behavior for free.
No ARIA is better than bad ARIA — always prefer a native semantic element over adding ARIA attributes to a generic <div>. ARIA should fill gaps, not replace semantics you could get for free.
It provides an accessible name for an element when there is no visible text to describe it, such as an icon-only button.
Many users navigate exclusively via keyboard or other assistive technology, not a mouse. Every interactive element must be reachable with Tab and operable with Enter or Space.
HTML Comments
Q19. How do you write a comment in HTML?
With <!-- comment text -->. Anything between the markers is ignored by the browser and never rendered.
Q20. Are HTML comments visible to users?
Not in the rendered page, but anyone can see them by viewing the page source, so sensitive information should never be placed inside a comment.
Q21. Can HTML comments be nested?
No. Placing <!-- --> inside another comment closes the outer comment early, which can produce broken or unexpected markup.