HTML Interview Questions and Answers
These HTML interview questions cover what front-end and full-stack interviews ask most, from document structure and semantic elements to forms, accessibility, responsive images, script loading and SEO markup. They are grouped into fresher, intermediate and advanced levels; read the direct answer first, then use the code examples and tips to prepare for follow-up questions.
HTML interview questions: fresher level
What is HTML, and is it a programming language?
HTML (HyperText Markup Language) is the standard markup language that describes the structure and meaning of content on a web page. It is not a programming language: it has no variables, conditions, loops or functions. You wrap content in elements such as headings, paragraphs, links and images, and the browser parses that markup into the DOM (Document Object Model), which CSS styles and JavaScript can read and change.
Think of the three core web technologies as layers: HTML gives structure and meaning, CSS handles presentation, and JavaScript adds behaviour.
Interview tip: If you call HTML a programming language, expect a follow-up asking you to explain the difference between markup and programming.
What are the main features introduced in HTML5?
HTML5 is the common name for the modern HTML standard, which is now maintained by WHATWG as a continuously updated Living Standard rather than as numbered versions. The features usually expected in an answer are:
- Semantic elements such as
header,nav,main,article,section,aside,footerandfigure. - Native
audioandvideoelements, so media no longer needs plugins like Flash. - New input types (
email,date,range,color) and built-in validation withrequiredandpattern. canvasfor drawing with JavaScript, and inline SVG.- Browser APIs that arrived alongside it, such as Web Storage (
localStorage,sessionStorage), Geolocation, drag and drop, and Web Workers. - The short
<!DOCTYPE html>declaration and customdata-*attributes.
What is the purpose of the DOCTYPE declaration?
<!DOCTYPE html> tells the browser to render the page in standards mode, and it must be the very first thing in the file. Without it, browsers fall back to quirks mode, which imitates the behaviour of very old browsers, so the box model and some layout calculations can differ from what modern CSS expects.
The DOCTYPE is not an HTML element, and it is case-insensitive. The short modern form does not reference a DTD, unlike the long HTML 4.01 and XHTML declarations.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Standards mode page</title>
</head>
<body>...</body>
</html>Interview tip: A common follow-up is "What is quirks mode?"; say it exists only so that very old pages keep rendering the way they used to.
What is the basic structure of an HTML document?
Every page starts with the DOCTYPE, followed by one root html element that contains exactly two children: head and body.
htmlwraps everything. Itslangattribute, such aslang="en", helps screen readers pronounce text correctly and helps translation tools.headholds metadata that is not displayed: thetitle, meta tags, stylesheets, scripts and icons.bodyholds everything the user sees and interacts with.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>My First Page</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>Hello, world</h1>
</body>
</html>A valid document needs a title. It appears in the browser tab and is usually the clickable headline in search results.
What are semantic elements, and why do they matter?
Semantic elements describe the meaning of their content, not just its appearance. header, nav, main, article, section, aside, footer, figure and time tell the browser what role a block plays, whereas div and span say nothing at all.
- Accessibility: screen readers expose many of them as landmarks, so users can jump straight to the navigation or the main content.
- SEO: search engines get clearer signals about which part of the page is the main content.
- Maintainability: the markup is far easier to read than a wall of nested divs.
<body>
<header>Logo and site title</header>
<nav>Main menu</nav>
<main>
<article>
<h1>Blog post title</h1>
<p>Post content...</p>
</article>
<aside>Related posts</aside>
</main>
<footer>Copyright notice</footer>
</body> Interview tip: A frequent follow-up is article versus section: an article makes sense on its own (a blog post, a product card), while a section is a themed part of something larger.
What is the difference between block-level and inline elements?
A block-level element starts on a new line and stretches to fill the available width; an inline element sits inside a line of text and is only as wide as its content.
- Block examples:
div,p,h1toh6,ul,section,form. - Inline examples:
span,a,strong,em,code,label. - On non-replaced inline elements such as
span,widthandheightare ignored, and vertical margins do not push the surrounding lines away. display: inline-blockflows inline but respects width, height and vertical spacing.
Strictly speaking, this behaviour comes from each element's default CSS display value, and any element can be changed with CSS. The HTML spec itself groups elements into content categories such as flow content and phrasing content.
What is the difference between div and span?
Both are generic containers with no meaning of their own; the difference is that div is block-level and span is inline.
Use div to group larger chunks of layout, such as a card or a flex wrapper. Use span to target a piece of text inside a line, for example to colour a single word or price. Reach for either one only when no semantic element fits: if the wrapper is really navigation, a list or an article, use nav, ul or article instead.
<div class="card">
<h2>HTML Basics</h2>
<p>Fee: <span class="price">₹499</span></p>
</div>
What is the difference between the id and class attributes?
An id must be unique within the page and identifies exactly one element; a class can be shared by many elements, and one element can have several classes separated by spaces.
idis used for fragment links (href="#pricing"), for connecting alabelto an input, and withdocument.getElementById().classis the normal hook for styling and for selecting groups of elements withquerySelectorAll().- In CSS, an id selector has higher specificity than a class selector, so id-based styles are harder to override. That is why most teams style with classes.
<section id="pricing" class="card card-highlight">
...
</section>
<a href="#pricing">See pricing</a>
Which meta tags should every page have, and what do they do?
Three are close to mandatory: charset, viewport and description.
meta charset="UTF-8"tells the browser how to decode the bytes of the file. Put it first in thehead(it must appear within the first 1024 bytes), otherwise characters such as ₹ or Hindi text can turn into garbage.meta name="viewport" content="width=device-width, initial-scale=1"makes mobile browsers lay the page out at the device width instead of a zoomed-out desktop width. Without it, media queries do not behave as expected on phones.meta name="description"is a short summary of the page. It does not directly affect rankings, but search engines often show it as the snippet under your title.
Avoid user-scalable=no in the viewport tag, because blocking pinch-zoom hurts users with low vision. The old meta name="keywords" tag is ignored by Google.
How should headings from h1 to h6 be used?
Headings form the outline of a page, so choose the level by importance and nesting, never by font size. Use one h1 for the main topic, h2 for major sections, h3 for sub-sections inside an h2, and so on, without skipping levels.
Screen reader users often move through a page by jumping from heading to heading, and search engines use headings to understand structure. If you want an h2 to look smaller, change it with CSS instead of picking an h4 for its size.
<h1>HTML Interview Questions</h1>
<h2>Forms</h2>
<h3>Input types</h3>
<h3>Validation</h3>
<h2>Accessibility</h2> Interview tip: Several h1 elements are not invalid HTML, but one h1 per page is the widely recommended practice; stating that nuance shows you know the difference between the spec and best practice.
Why is the alt attribute important on images?
alt provides a text alternative for the image: screen readers read it aloud, browsers display it if the image fails to load, and search engines use it to understand what the image shows.
- Describe what the image conveys in context.
alt="Student solving a JavaScript problem on a laptop"is useful;alt="image"is not. - For purely decorative images, use an empty value,
alt="", so assistive technology skips them. - Never leave
altout entirely; many screen readers then read the file name instead. - Skip phrases like "Image of", because screen readers already announce it as an image.
- When an image is the only content of a link, the alt text should describe where the link goes.
Interview tip: The difference between a missing alt and an empty alt="" is a favourite follow-up question.
What types of lists does HTML have?
There are three: unordered lists (ul), ordered lists (ol) and description lists (dl).
ulis for items where order does not matter, such as features or a navigation menu.olis for steps or rankings. It supportsstart,reversedandtype(for exampletype="A"ortype="i").dlpairs terms (dt) with descriptions (dd), which suits glossaries, FAQs and key-value details.
Apart from script-supporting elements such as template, only li may be a direct child of ul or ol. To nest a list, put the inner list inside an li.
<ol start="3">
<li>Install Node.js</li>
<li>Create a project
<ul>
<li>Run npm init</li>
</ul>
</li>
</ol>
What does target="_blank" do, and why add rel="noopener"?
target="_blank" opens the link in a new tab or window. Historically, the new page received a window.opener reference to your page and could use it to redirect your tab to a fake login page, an attack known as reverse tabnabbing.
rel="noopener" makes window.opener null in the new page. rel="noreferrer" does the same and also stops the browser from sending the Referer header. Modern browsers now treat target="_blank" links as noopener by default, but writing it explicitly is still common practice and protects users on older browsers.
<a href="/downloads/syllabus.pdf" target="_blank" rel="noopener noreferrer">
Download syllabus
</a>
What are void elements in HTML?
Void elements cannot have any content, so they have a start tag and never an end tag. The list is fixed: area, base, br, col, embed, hr, img, input, link, meta, source, track and wbr.
In HTML, a trailing slash on a void element is allowed but ignored by the parser; it is required only in XHTML and JSX. A slash on a non-void element does nothing, so the browser treats it as an ordinary start tag that is still open.
<img src="logo.png" alt="Logo"> <!-- correct -->
<img src="logo.png" alt="Logo" /> <!-- also fine, slash ignored -->
<br>
<div /> <!-- NOT closed: this is still an open div -->
What are HTML entities, and when do you need them?
Entities are codes that represent characters which would otherwise be read as markup or are hard to type. They start with & and end with ;, and can be named (©) or numeric (© in decimal, © in hex).
<and>display the less-than and greater-than signs as text instead of starting a tag.&for an ampersand, and"for a double quote inside a double-quoted attribute value. is a non-breaking space that keeps two words on the same line, such as a number and its unit.
With UTF-8 you can type characters like ©, ₹ or é directly, so entities are mainly needed for the reserved characters. When inserting user text with JavaScript, use textContent, which never parses HTML, instead of escaping by hand for innerHTML.
<p>Fee: ₹999</p>
<p>© All rights reserved</p>
How do you build a table in HTML, and what are colspan and rowspan?
A table is made of rows (tr) that contain header cells (th) or data cells (td), grouped into thead, tbody and optionally tfoot. colspan makes a cell stretch across several columns, and rowspan across several rows.
<table>
<thead>
<tr><th>Course</th><th>Weekday</th><th>Weekend</th></tr>
</thead>
<tbody>
<tr><td>HTML</td><td>7 PM</td><td>10 AM</td></tr>
<tr><td>React</td><td colspan="2">Recorded only</td></tr>
<tr><td rowspan="2">Projects</td><td>Mon</td><td>Sat</td></tr>
<tr><td>Wed</td><td>Sun</td></tr>
</tbody>
</table>The row groups help browsers, screen readers and printing; for example, a long table can repeat its header on each printed page. Use tables only for tabular data, never for page layout, which is the job of CSS Grid and Flexbox.
HTML interview questions: intermediate level
Which HTML5 input types do you know, and why use them instead of type="text"?
HTML5 added types such as email, url, tel, number, range, date, time, datetime-local, month, week, color and search, alongside older ones like password, checkbox, radio, file and hidden.
- Better mobile keyboards:
emailshows an @ key andtelshows a phone keypad. - Built-in validation:
emailandurlreject badly formatted values on submit, andnumbersupportsmin,maxandstep. - Native pickers:
dateandcolorgive a picker without any JavaScript.
tel does no format validation, because phone formats differ by country; add a pattern if you need one. For identifiers such as PIN codes or OTPs, prefer type="text" with inputmode="numeric": they are not quantities, and number adds spinner arrows that can change the value by accident.
Why should every input have a label, and how do you associate them?
A label gives an input its accessible name, so screen readers announce what the field is for. Clicking the label also focuses or toggles the input, which gives small checkboxes and radio buttons a bigger tap target.
There are two ways to connect them: match the label's for attribute to the input's id, or wrap the input inside the label. A placeholder is not a substitute, because it disappears as soon as the user starts typing and makes a poor accessible name.
<label for="email">Email address</label>
<input type="email" id="email" name="email">
<label>
<input type="checkbox" name="terms"> I accept the terms
</label>
What is the difference between the name and id attributes on a form field?
name is the key under which the field's value is sent to the server; id is a unique identifier used inside the page by labels, CSS and JavaScript.
A field without a name is not submitted at all, even if it has a value. name does not have to be unique: radio buttons share one name so that only one can be selected, and only the selected button's value is sent. An id, by contrast, must be unique in the whole document.
<input type="radio" id="mode-online" name="mode" value="online">
<label for="mode-online">Online</label>
<input type="radio" id="mode-offline" name="mode" value="offline">
<label for="mode-offline">Offline</label>
<!-- Submits mode=online or mode=offline --> Interview tip: A related trap: disabled fields and unchecked checkboxes are not submitted, but readonly fields are.
What is the difference between GET and POST in a form?
With method="get", which is the default, form data is appended to the URL as a query string; with method="post", it is sent in the request body.
- GET suits searches and filters: the URL can be bookmarked, shared and cached, and refreshing is harmless.
- POST suits actions that change data, such as sign-up, login or payment, and larger payloads. Refreshing triggers the browser's resubmission warning.
- File uploads need POST together with
enctype="multipart/form-data".
POST is not encryption: the body is visible in dev tools and on the network unless the site uses HTTPS. GET simply exposes data more easily, because URLs end up in browser history and server logs, so never send passwords with GET.
<form action="/search" method="get">
<input type="search" name="q">
<button>Search</button>
</form>
<!-- Typing flexbox submits to /search?q=flexbox -->Interview tip: Expect "Is POST more secure than GET?"; the accurate answer is that HTTPS provides the security, not the method.
How does built-in HTML form validation work?
The browser checks constraint attributes when the form is submitted and blocks submission, showing a message, if any field is invalid. No JavaScript is required.
required: the field cannot be empty.minlengthandmaxlengthlimit text length;min,maxandsteplimit numbers and dates.pattern: a regular expression that the whole value must match, because it is implicitly anchored, so no^or$is needed. An empty field passespatternunless it is alsorequired.type="email"andtype="url"add format checks.
<form>
<input name="pincode" required pattern="[0-9]{6}"
inputmode="numeric" title="6-digit PIN code">
<button>Submit</button>
</form>Add novalidate to the form to switch it off, or use the Constraint Validation API (checkValidity(), setCustomValidity()) to customise it. Client-side checks only improve user experience; always validate again on the server.
What are fieldset and legend used for?
fieldset groups related controls in a form, and legend, placed as its first child, gives that group a caption. Screen readers announce the legend when the user moves into the group, which is essential for radio buttons and checkboxes whose labels alone, such as "Yes" or "No", would be meaningless.
Adding disabled to a fieldset disables every control inside it, except those inside its legend, which is handy for multi-step forms.
<fieldset>
<legend>Preferred batch</legend>
<label><input type="radio" name="batch" value="morning"> Morning</label>
<label><input type="radio" name="batch" value="evening"> Evening</label>
</fieldset>
What is the difference between async and defer on script tags?
Both download the script in parallel without blocking HTML parsing; they differ in when the script runs.
- No attribute: parsing stops while the script downloads and executes, which is why scripts were traditionally placed at the end of
body. async: runs as soon as it has downloaded, pausing the parser at that moment. The order between async scripts is not guaranteed, so it suits independent scripts such as analytics.defer: runs after the whole document has been parsed, in the order the scripts appear, before theDOMContentLoadedevent. It suits application code that needs the DOM or depends on other scripts.
<script src="analytics.js" async></script>
<script src="vendor.js" defer></script>
<script src="app.js" defer></script> <!-- runs after vendor.js -->Both attributes apply only to external classic scripts with a src. Scripts with type="module" are deferred by default.
Interview tip: If asked which attribute is safe when one script depends on another, answer defer, because it preserves document order.
What is the difference between localStorage, sessionStorage and cookies?
All three store small strings in the browser, but they differ in lifetime, scope and whether the server sees them.
- localStorage: persists until cleared by code or the user, is shared by all tabs of the same origin, holds a few megabytes, and is never sent to the server automatically.
- sessionStorage: the same API, but scoped to a single tab and cleared when that tab closes.
- Cookies: about 4 KB each, can have an expiry date, and are sent with every matching HTTP request, so the server can read them.
HttpOnly,SecureandSameSiteflags control access.
localStorage.setItem('theme', 'dark');
localStorage.getItem('theme'); // "dark"
localStorage.setItem('user', JSON.stringify({ id: 7 }));
JSON.parse(localStorage.getItem('user')).id; // 7
sessionStorage.setItem('step', '2');Values are always strings, so objects need JSON.stringify. Any script on the page can read web storage, so an XSS bug can leak it; sensitive session tokens are safer in HttpOnly cookies.
What are data-* attributes, and how do you access them in JavaScript?
Custom data-* attributes let you attach extra information to an element without inventing non-standard attributes. Any name after data- is allowed as long as it contains no uppercase letters, and the value is always a string.
<button class="add" data-course-id="42" data-price="4999">Add to cart</button>const btn = document.querySelector('.add');
btn.dataset.courseId; // "42" (a string)
Number(btn.dataset.price); // 4999
btn.dataset.status = 'added'; // adds data-status="added"In JavaScript, read and write them through the dataset property, where hyphenated names become camelCase. In CSS, target them with attribute selectors such as [data-status="added"]. Use them for small hints to scripts and styles, not as storage for anything sensitive, since everything is visible in the page source.
How do srcset, sizes and the picture element help with responsive images?
They let the browser download an image suited to the device, instead of sending a large desktop image to every phone.
srcsetwithwdescriptors lists the same image at several widths;sizestells the browser how wide the image will be displayed, so it can pick the best file for the screen size and pixel density.srcsetwithxdescriptors (1x,2x) suits fixed-size images such as logos.picturewithsourcechildren handles art direction (a different crop at a breakpoint, usingmedia) and format fallback (AVIF or WebP with a JPEG fallback, usingtype). The innerimgis required: it is what actually renders and it carries thealt.
<img src="hero-800.jpg" alt="Classroom session"
srcset="hero-400.jpg 400w, hero-800.jpg 800w, hero-1600.jpg 1600w"
sizes="(max-width: 600px) 100vw, 50vw">
<picture>
<source srcset="banner.avif" type="image/avif">
<source srcset="banner.webp" type="image/webp">
<img src="banner.jpg" alt="Workshop banner" width="1200" height="600">
</picture> Interview tip: With plain srcset the browser makes the final choice; a picture source with media is the way to force a specific image at a breakpoint.
Why add width, height and loading="lazy" to images?
width and height let the browser reserve the right space before the image downloads, which stops the layout from jumping, a problem measured as Cumulative Layout Shift (CLS) in Core Web Vitals. Modern browsers derive the aspect ratio from these attributes, so the image can still be responsive with CSS.
<img src="team.jpg" alt="Our mentors" width="1200" height="800" loading="lazy">
<style>
img { max-width: 100%; height: auto; }
</style>loading="lazy" delays downloading off-screen images until the user scrolls near them, saving data and speeding up the first load. It also works on iframe. Do not lazy-load the main above-the-fold image, which is often the Largest Contentful Paint (LCP) element, because that delays it; for that image, fetchpriority="high" can help instead.
How do you embed audio and video in HTML5?
Use the native audio and video elements; no plugin is needed. Add controls to show the browser's play, volume and seek UI, and list several source elements so the browser picks the first format it supports.
<video controls width="640" poster="intro-thumb.jpg" preload="metadata">
<source src="intro.webm" type="video/webm">
<source src="intro.mp4" type="video/mp4">
<track kind="captions" src="intro-en.vtt" srclang="en" label="English">
Your browser does not support HTML video.
</video>postershows an image before playback starts;preloadhints how much to download in advance.trackadds captions or subtitles in WebVTT format, which matters for accessibility.- Browsers generally block autoplay with sound, so
autoplayis reliable only together withmuted. Addplaysinlineso iPhones play the video inside the page instead of going full screen.
What is an iframe, and what security concerns come with it?
An iframe embeds another HTML document inside the current page, commonly for maps, videos, payment widgets and ads. Each iframe is a separate browsing context with its own DOM.
- Give every iframe a
titleso screen readers can describe it. sandboxapplies strict restrictions (no scripts, no form submission, no popups, a unique origin); you re-enable only what you need, such assandbox="allow-scripts".allowcontrols access to features such as the camera, fullscreen or geolocation.loading="lazy"defers off-screen embeds.
<iframe src="/embed/map.html" title="Institute location map"
width="600" height="400" loading="lazy"
sandbox="allow-scripts"></iframe>The reverse risk is clickjacking: an attacker loads your site in an invisible iframe and tricks users into clicking it. Prevent that with the Content-Security-Policy: frame-ancestors header or the older X-Frame-Options header.
Interview tip: Combining allow-scripts with allow-same-origin for same-origin content lets the framed page remove its own sandbox, which is a classic follow-up trap.
How do you make a data table accessible?
Screen readers announce the matching headers as a user moves between cells, but only if the table marks its headers up properly.
- Use
thfor header cells, not boldtdcells. - Add
scope="col"orscope="row"so it is clear which cells each header describes. For complex tables with multi-level headers, give headers anidand reference them from data cells withheaders. - Add a
captionas the first child oftableto give the table a name. - Group rows with
thead,tbodyandtfoot. - Never use tables for layout; if you inherit one,
role="presentation"removes its table semantics.
<table>
<caption>Course fees</caption>
<thead>
<tr><th scope="col">Course</th><th scope="col">Fee</th></tr>
</thead>
<tbody>
<tr><th scope="row">HTML and CSS</th><td>₹2,999</td></tr>
</tbody>
</table>
What is the difference between canvas and SVG?
canvas is a bitmap you draw on with JavaScript; SVG is an XML-based vector format whose shapes become DOM elements.
- Scaling: SVG stays sharp at any zoom level; canvas is pixels and blurs when scaled unless you redraw at a higher resolution.
- Interaction: each SVG shape can have CSS, event listeners and accessible text. Once drawn on a canvas, shapes are just pixels, so you track positions yourself to detect clicks.
- Performance: canvas handles thousands of moving objects well; SVG slows down when its DOM grows very large.
- Typical use: SVG for icons, logos, charts and illustrations; canvas for games, real-time visualisations and pixel-level image editing.
<svg width="100" height="100" role="img" aria-label="Green circle">
<circle cx="50" cy="50" r="40" fill="green" />
</svg>
<canvas id="c" width="100" height="100"></canvas>
<script>
const ctx = document.getElementById('c').getContext('2d');
ctx.fillStyle = 'green';
ctx.beginPath();
ctx.arc(50, 50, 40, 0, Math.PI * 2);
ctx.fill();
</script>HTML interview questions: advanced level
What is the difference between an HTML attribute and a DOM property?
Attributes are written in the HTML source and are always strings; properties live on the DOM object the browser builds from that markup and can be of any type. Many attributes are reflected to a property of the same name, but the two are not always in sync.
// HTML: <input id="city" value="Pune">
const input = document.getElementById('city');
input.value = 'Delhi'; // same effect as the user typing
console.log(input.getAttribute('value')); // "Pune"
console.log(input.value); // "Delhi"
console.log(input.defaultValue); // "Pune"- The
valueattribute only sets the initial value, while thevalueproperty tracks the current one. Thecheckedattribute and property of a checkbox behave the same way. - Names can differ: the
classattribute maps toclassName(orclassList), andformaps tohtmlFor. - Values can differ: the
hrefproperty of a link returns the fully resolved URL, whilegetAttribute('href')returns exactly what was written. - Custom attributes do not create properties; read them with
getAttribute()ordataset.
Interview tip: This often leads into React, where JSX uses className and htmlFor because its props follow DOM property names.
When should you use ARIA, and when should you avoid it?
Use ARIA only when native HTML cannot express what you need. The first rule of ARIA is: if a native element or attribute already provides the semantics and behaviour, use that instead.
A button is focusable, responds to Enter and Space, and is announced as a button for free. A div with role="button" is only announced as a button; you must add tabindex and keyboard handling yourself. Incorrect ARIA is worse than none, because it actively misleads screen reader users.
- Valid uses: custom widgets with no native equivalent (tabs, comboboxes), states such as
aria-expandedon a menu toggle,aria-livefor content that updates dynamically, andaria-labelfor icon-only buttons. aria-hidden="true"hides decorative content from assistive technology; never put it on a focusable element.
<button aria-label="Close dialog">✕</button>
<button aria-expanded="false" aria-controls="faq-1">What is HTML?</button>
<div id="faq-1" hidden>HTML is a markup language...</div>
<p aria-live="polite" id="cart-status"></p> Interview tip: If you are asked to fix a clickable div, the best answer is to replace it with a real button rather than adding ARIA to it.
What are landmark regions, and how do HTML elements map to them?
Landmarks are the major regions of a page that assistive technology can list, so a screen reader user can jump straight to the navigation or the main content instead of tabbing through everything. Semantic HTML elements create them implicitly.
headermaps tobannerandfootertocontentinfo, but only when they are not nested insidearticle,aside,main,navorsection.navmaps tonavigation,maintomain, andasidetocomplementary.sectionbecomes aregionlandmark, andformaformlandmark, only when it has an accessible name, for example througharia-labelledby.
Use one visible main per page. When a page has two nav elements, label them, for example aria-label="Primary" and aria-label="Footer", so users can tell them apart. Adding role="main" to a main element is redundant.
Which HTML markup matters most for SEO?
Markup cannot make weak content rank, but clean HTML helps search engines crawl, understand and display a page correctly.
- A unique, descriptive
titleper page, plus ameta name="description"that summarises it for the search snippet. - A logical heading hierarchy with one clear
h1, and semantic elements around the main content. - Real
aelements withhreffor navigation and descriptive anchor text; crawlers do not clickdivelements wired up with JavaScript. - Meaningful
alttext on content images. link rel="canonical"with the preferred absolute URL when the same content is reachable at several URLs, andmeta name="robots" content="noindex"for pages that should stay out of results.- Structured data in a
script type="application/ld+json"block using the schema.org vocabulary, which can make a page eligible for rich results.
Open Graph tags such as og:title and og:image control link previews in social and messaging apps; they are not a ranking factor.
Interview tip: Interviewers like to hear that meta keywords is ignored by Google and that the meta description affects click-through, not ranking.
When should you use a button and when should you use a link?
Use an a element with href when the action navigates to a URL; use button when it performs an action on the current page, such as submitting a form, opening a modal or toggling a menu.
- Links get open-in-new-tab, copy-link, middle-click and crawling for free; buttons do not.
- Keyboard behaviour differs: links activate with Enter, buttons with Enter and Space.
- Screen readers announce them differently, so the wrong element misleads users about what will happen.
A common bug: a button inside a form defaults to type="submit", so a "Show password" button submits the form. Set type="button" on non-submit buttons. Also, an a without href is not focusable, and href="#" with a click handler is really a button in disguise.
<form>
<input type="password" id="pwd" name="pwd">
<button type="button" id="toggle">Show</button>
<button type="submit">Log in</button>
</form>
What does the browser do with invalid HTML, such as a div inside a p?
Browsers never reject a page for invalid markup. The HTML parsing algorithm defines exact error-recovery rules, so modern browsers build the same DOM from the same broken source, though not always the DOM you intended.
<!-- Source -->
<p>Intro <div>Box</div> text</p>
<!-- Resulting DOM -->
<p>Intro </p>
<div>Box</div>
text
<p></p>A p may contain only phrasing content, so the div start tag closes the paragraph automatically, and the stray closing p tag then creates an empty paragraph. Similar recovery happens for unclosed tags and misnested b and i elements. This is why DevTools can show a structure different from your source, and why CSS selectors or innerHTML results sometimes surprise you. Running a validator catches these problems early.
Interview tip: Mentioning that error handling is fully specified, which is why results are consistent across browsers, is the detail that stands out.
How does tabindex work, and how do you make a page keyboard accessible?
tabindex controls whether an element can receive keyboard focus and where it sits in the Tab order.
tabindex="0"adds a normally non-focusable element, such as a custom widget, to the natural Tab order based on its DOM position.tabindex="-1"makes an element focusable only from script withelement.focus(), which is useful for moving focus to a modal or an error summary.- Positive values such as
tabindex="3"jump ahead of everything else and create a confusing order, so avoid them.
Beyond tabindex: prefer native interactive elements, keep DOM order matching visual order, never remove the focus outline without a visible replacement (:focus-visible helps), keep focus inside an open modal and return it when the modal closes, and provide a skip link.
<a class="skip-link" href="#main">Skip to main content</a>
<!-- header and navigation -->
<main id="main" tabindex="-1">...</main>
What is the template element, and how is it used?
template holds a fragment of HTML that the browser parses but does not render. Its content is inert: images inside it do not load, scripts do not run, and nothing appears on the page until you clone it with JavaScript.
<template id="row-tpl">
<li class="student"><span class="name"></span></li>
</template>
<ul id="list"></ul>
<script>
const tpl = document.getElementById('row-tpl');
for (const name of ['Asha', 'Ravi']) {
const row = tpl.content.cloneNode(true);
row.querySelector('.name').textContent = name;
document.getElementById('list').appendChild(row);
}
</script>This is cleaner and safer than building HTML strings for innerHTML, because user data goes in through textContent. template is also the usual way to define the markup of Web Components, often combined with Shadow DOM and slot elements.
What are render-blocking resources, and how do preload and preconnect help?
By default, the browser does not paint the page until the stylesheets in the head have loaded, and classic scripts without async or defer stop the parser. Large or slow blocking resources delay the first paint.
- Load non-critical JavaScript with
deferorasync. - Keep critical CSS small; a stylesheet whose
mediaattribute does not match, such asmedia="print", does not block rendering. link rel="preload"fetches a resource needed soon, such as a font or the hero image, at high priority. It needs a correctasattribute, and fonts also needcrossorigin.link rel="preconnect"sets up the connection (DNS, TCP, TLS) to another origin early, such as a font or CDN host;dns-prefetchdoes only the DNS lookup.
<head>
<link rel="preload" href="/fonts/inter.woff2" as="font" type="font/woff2" crossorigin>
<link rel="stylesheet" href="/css/main.css">
<link rel="stylesheet" href="/css/print.css" media="print">
<script src="/js/app.js" defer></script>
</head>How good is your HTML, really?
Take the 15-question HTML, CSS and JavaScript challenge. Miss one and you get a short explanation plus a second chance to win the point back. At the end you see exactly where you stand, and which class to take next.
- 15 questions
- About 10 minutes
- 100% free