1. What is HTML?
HTML (HyperText Markup Language) is the standard markup language used to structure content on the web. It uses elements, written as tags, to describe headings, paragraphs, links, images, forms and more. Browsers parse HTML into the DOM and render it. HTML defines meaning and structure, while CSS handles presentation and JavaScript handles behavior. The current living standard is maintained by WHATWG and is commonly called HTML5.
2. What is the basic structure of an HTML5 document?
An HTML5 document starts with <!DOCTYPE html>, followed by a root <html> element containing a <head> and a <body>. The <head> holds metadata such as <title>, <meta> tags, stylesheets and scripts. The <body> holds the visible content. Setting lang on <html> and a charset meta tag is considered best practice.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Page title</title>
</head>
<body>
<h1>Hello</h1>
</body>
</html>
3. What is the purpose of the DOCTYPE declaration?
The <!DOCTYPE html> declaration tells the browser to render the page in standards mode instead of quirks mode. Without it, browsers emulate legacy behavior, which can cause inconsistent box sizing and layout. It is not an HTML tag, and it is case-insensitive. In HTML5 it is short and simple, unlike the long DOCTYPEs of HTML 4 and XHTML.
4. What are semantic HTML elements and why are they important?
Semantic elements clearly describe their meaning to both the browser and the developer, for example <header>, <nav>, <main>, <article>, <section>, <aside> and <footer>. They improve accessibility because assistive technologies expose them as landmarks. They also help SEO and make code easier to read and maintain compared with generic <div> and <span> elements.
<header>Site header</header>
<nav>Menu</nav>
<main>
<article>Post content</article>
<aside>Related links</aside>
</main>
<footer>Copyright</footer>
5. What is the difference between block-level and inline elements?
Block-level elements start on a new line and take up the full available width, while inline elements flow within a line and take only the width of their content. Examples of block elements are <div>, <p>, <h1> and <ul>. Examples of inline elements are <span>, <a>, <strong> and <img>. Inline elements ignore vertical width and height settings, but CSS display can change this behavior.
6. What is the difference between `<div>` and `<span>`?
<div> is a generic block-level container, and <span> is a generic inline container. Neither carries any meaning on its own. Use <div> to group blocks of content for layout or styling, and <span> to style or target a small piece of text inside a line. Prefer semantic elements when one fits the content.
7. What is the difference between `<section>`, `<article>` and `<div>`?
<article> is a self-contained piece of content that makes sense on its own, such as a blog post or news item. <section> is a thematic grouping of content that normally has its own heading. <div> has no semantic meaning and is used only for styling or scripting hooks. Choose <article> or <section> when the meaning applies, and fall back to <div> otherwise.
8. What are meta tags and which ones matter most?
Meta tags provide metadata about the document and live inside <head>. The most important are charset for character encoding, viewport for responsive mobile layout, and description for the search result snippet. Open Graph tags control social sharing previews, and robots controls indexing. The <title> element is not a meta tag but is equally important for SEO.
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="Short page summary">
<meta name="robots" content="index, follow">
9. What is the difference between `id` and `class` attributes?
An id must be unique within a page and identifies exactly one element, while a class can be shared by many elements and one element can have several classes. In CSS, ids are selected with # and classes with ., and ids have higher specificity. Ids are also used for fragment links, label associations and ARIA references. Classes are the usual choice for reusable styling.
10. How do you create links in HTML, and what does the `target` attribute do?
Links are created with the anchor element <a> and its href attribute. The target attribute sets where the link opens, and _blank opens a new tab or window. When using target="_blank", modern browsers imply rel="noopener", but adding rel="noopener noreferrer" is still common practice for older browsers and to hide the referrer.
<a href="https://example.com" target="_blank" rel="noopener noreferrer">Visit</a>
11. Why is the `alt` attribute important on images?
The alt attribute provides a text alternative for an image, which screen readers announce and browsers show if the image fails to load. It is also used by search engines to understand the image. Write short, meaningful descriptions for informative images, and use an empty alt="" for purely decorative images so assistive technology skips them. The attribute is required for valid HTML.
12. What are the new input types introduced in HTML5?
HTML5 added input types such as email, url, tel, number, range, date, time, datetime-local, month, week, color and search. They provide built-in validation, appropriate mobile keyboards and native pickers. Browsers that do not support a type fall back to a plain text input, so the form still works.
<input type="email" required>
<input type="date">
<input type="range" min="0" max="10">
<input type="color">
13. How does HTML5 form validation work?
HTML5 provides built-in client-side validation through attributes like required, pattern, min, max, minlength, maxlength and type. When the form is submitted, the browser blocks submission and shows an error message if a field is invalid. The novalidate attribute on the form turns this off. Client-side validation improves user experience but must always be repeated on the server.
<form>
<input type="text" name="zip" pattern="[0-9]{5}" required>
<button type="submit">Send</button>
</form>
14. What is the purpose of the `<label>` element and how do you associate it with an input?
The <label> element gives an input an accessible name and enlarges its click target, since clicking the label focuses or toggles the control. You associate it either by matching the label's for attribute to the input's id, or by nesting the input inside the label. Every form control should have a label for accessibility.
<label for="email">Email</label>
<input id="email" type="email" name="email">
15. What is the difference between GET and POST methods in a form?
GET appends form data to the URL as a query string, while POST sends it in the request body. GET is meant for safe, idempotent requests such as search, and results can be bookmarked and cached, but data is visible in the URL and length is limited. POST is used for actions that change data or send sensitive or large payloads. Neither method is secure without HTTPS.
16. What is the difference between `async` and `defer` on script tags?
Both download the script in parallel with HTML parsing, but they differ in when it runs. async executes the script as soon as it is downloaded, pausing parsing, and execution order is not guaranteed. defer waits until the document is parsed and runs scripts in order before DOMContentLoaded. Use defer for scripts that depend on the DOM or each other, and async for independent scripts like analytics.
<script src="app.js" defer></script>
<script src="analytics.js" async></script>
17. What are `data-*` attributes and how do you use them?
data-* attributes let you store custom data on any HTML element without affecting rendering. The name after data- is your own choice. In JavaScript you read them through the dataset property, where hyphenated names become camelCase. In CSS you can select them with attribute selectors. They are useful for passing small bits of information to scripts.
<button data-user-id="42" data-role="admin">Edit</button>
<script>
const btn = document.querySelector("button");
console.log(btn.dataset.userId);
</script>
18. What are `localStorage`, `sessionStorage` and cookies, and how do they differ?
All three store data in the browser. localStorage persists until it is cleared and is shared across tabs of the same origin. sessionStorage lasts only for the tab session. Both hold roughly 5 MB of strings and are never sent automatically to the server. Cookies are much smaller, around 4 KB, can have expiry dates and flags like HttpOnly and Secure, and are sent with every matching HTTP request.
19. How do you embed audio and video in HTML5?
Use the <audio> and <video> elements, which play media natively without plugins. Add the controls attribute for the built-in player, and provide several <source> elements in different formats so the browser picks one it supports. Include <track> for captions and subtitles to meet accessibility needs. Autoplay is usually blocked unless the media is muted.
<video controls width="480" poster="cover.jpg">
<source src="clip.mp4" type="video/mp4">
<source src="clip.webm" type="video/webm">
<track kind="captions" src="en.vtt" srclang="en" label="English">
</video>
20. What is an iframe and what are its security considerations?
An <iframe> embeds another HTML document inside the current page. Because embedded content can be untrusted, use the sandbox attribute to restrict scripts, forms and navigation, and set allow to control feature permissions. Servers can prevent their pages from being framed with the X-Frame-Options header or the CSP frame-ancestors directive, which protects against clickjacking. Add loading="lazy" and a title for performance and accessibility.
<iframe src="https://example.com" title="Example" sandbox="allow-scripts" loading="lazy"></iframe>
21. How do you make images responsive in HTML?
Use the srcset and sizes attributes on <img> so the browser picks the best file for the screen width and pixel density. Use the <picture> element for art direction or format switching, such as serving AVIF or WebP with a JPEG fallback. Always set width and height to avoid layout shift, and use CSS like max-width: 100% to keep images fluid.
<picture>
<source type="image/webp" srcset="hero.webp">
<img src="hero.jpg"
srcset="hero-480.jpg 480w, hero-1200.jpg 1200w"
sizes="(max-width: 600px) 100vw, 600px"
alt="Mountain view" width="1200" height="800">
</picture>
22. What is the viewport meta tag and why is it needed?
The viewport meta tag tells mobile browsers how to size and scale the page. Without it, phones render the page at a virtual desktop width of around 980px and shrink it down, which breaks responsive CSS and media queries. The standard setting is width=device-width, initial-scale=1. Avoid user-scalable=no or maximum-scale=1, since they block zooming and hurt accessibility.
23. What is ARIA and when should you use it?
ARIA (Accessible Rich Internet Applications) is a set of attributes such as role, aria-label, aria-labelledby and aria-expanded that add accessibility information for assistive technologies. The first rule of ARIA is to use native semantic HTML when possible, since a real <button> is better than a div role="button". Use ARIA only to fill gaps in custom widgets, and remember it changes semantics but not behavior or keyboard support.
<button aria-expanded="false" aria-controls="menu">Menu</button>
<ul id="menu" hidden>...</ul>
24. How do you optimize an HTML page for SEO?
Use a unique, descriptive <title> and meta description, a single clear <h1>, and a logical heading hierarchy. Write semantic markup, descriptive link text and meaningful alt text. Add a canonical link, structured data such as JSON-LD, and a mobile-friendly viewport. Fast loading, clean URLs and a sitemap also help. Search engines rely on the content and structure the HTML provides.
25. What is the difference between `<b>` and `<strong>`, and between `<i>` and `<em>`?
<strong> and <em> carry meaning: strong importance and stress emphasis, which screen readers may convey in tone. <b> and <i> are purely presentational in intent, marking text that is stylistically offset, such as keywords or foreign terms, without added importance. Visually they look the same by default, bold and italic. Prefer <strong> and <em> when the meaning matters, and use CSS for pure styling.
26. What is the difference between `<script>`, `<script type="module">` and `<script nomodule>`?
<script type="module"> loads an ES module: it is deferred by default, runs in strict mode, has its own scope, and can use import and export. Classic scripts run in the global scope and block parsing unless marked async or defer. nomodule scripts are ignored by browsers that support modules, so they act as a fallback for very old browsers.
<script type="module" src="app.js"></script>
<script nomodule src="legacy.js"></script>
27. How do `preload`, `prefetch`, `preconnect` and `dns-prefetch` differ?
preload fetches a resource needed for the current page at high priority, such as a font or hero image. prefetch fetches a resource at low priority for a likely future navigation. preconnect opens the connection (DNS, TCP, TLS) to another origin early, and dns-prefetch only resolves the DNS name. Overusing them wastes bandwidth and can delay more important requests.
<link rel="preload" href="font.woff2" as="font" type="font/woff2" crossorigin>
<link rel="preconnect" href="https://cdn.example.com">
28. How does lazy loading work for images and iframes, and when should you avoid it?
Adding loading="lazy" tells the browser to delay fetching offscreen images and iframes until the user scrolls near them. This saves bandwidth and speeds up the initial load. Do not lazy-load the above-the-fold hero image or the likely Largest Contentful Paint element, because that delays it. Always set width and height so lazy images do not cause layout shift.
29. What are the `<template>` and `<slot>` elements used for?
<template> holds inert HTML that is parsed but not rendered, and its content is not active until JavaScript clones it into the document. This is a cheap way to stamp out repeated markup. <slot> is a placeholder inside a shadow DOM component where the host element's children are projected, which lets web components accept custom content.
<template id="row"><li class="item"></li></template>
<script>
const li = document.getElementById("row").content.cloneNode(true);
document.querySelector("ul").append(li);
</script>
30. What are Web Components and what are their main building blocks?
Web Components are a set of browser standards for building reusable, encapsulated elements without a framework. The main parts are custom elements (define your own tag with customElements.define), shadow DOM (scoped markup and styles), and <template> with <slot> for reusable structure. Custom element names must contain a hyphen, such as user-card, to avoid clashing with built-in tags.
31. What does the `<dialog>` element do, and how is it better than a custom modal?
<dialog> is a native dialog box. Calling showModal() opens it as a modal with a backdrop, traps focus inside, makes the rest of the page inert, and closes on the Escape key. Custom div modals need all of that built by hand and often get focus handling wrong. Use close() to dismiss it, and show() for a non-modal version.
<dialog id="dlg"><p>Hello</p><button onclick="dlg.close()">Close</button></dialog>
<button onclick="dlg.showModal()">Open</button>
32. How do `<details>` and `<summary>` work, and what are their limits?
<details> creates a native disclosure widget, and the first child <summary> is the always-visible toggle label. The browser handles open and close state, keyboard support and the open attribute with no JavaScript. Animating the open and close is awkward, and screen reader behavior varies, so test it. The name attribute can group several into an exclusive accordion.
33. What is wrong with this markup: `<a href="/buy"><button>Buy</button></a>`?
Interactive content must not be nested inside other interactive content, and a <button> inside an <a> is invalid HTML. It also creates two tab stops and unpredictable behavior in some browsers and screen readers. If it navigates, use an <a> styled with CSS to look like a button. If it performs an action, use a <button>.
34. What happens if you forget to close a tag, such as an unclosed `<div>`?
HTML parsing is forgiving, so the browser does not throw an error. It follows the parsing algorithm to repair the tree, often implicitly closing elements at the end of a parent or the document. The resulting DOM may differ from what you intended, causing broken layouts and styles leaking into later content. Run the page through the W3C validator or a linter to catch these mistakes.
35. How would you build an accessible custom dropdown or tab widget?
Start with native elements where possible, such as <select> or buttons. If you must build a custom widget, use the correct ARIA roles (for tabs, tablist, tab, tabpanel) with aria-selected and aria-controls. Manage keyboard support yourself: arrow keys to move, Home and End, Enter or Space to activate, and a roving tabindex. Always keep a visible focus style.
<div role="tablist">
<button role="tab" aria-selected="true" aria-controls="p1" id="t1">One</button>
<button role="tab" aria-selected="false" aria-controls="p2" id="t2" tabindex="-1">Two</button>
</div>
36. What is the difference between `hidden`, `display: none`, `visibility: hidden` and `aria-hidden`?
The hidden attribute applies display: none by default, so the element is removed from layout and from the accessibility tree. visibility: hidden hides it visually but keeps its space, and it is also skipped by assistive technology. aria-hidden="true" hides the element only from assistive technology while it stays visible on screen, so never put it on focusable elements.
37. How do you make a form field accessible beyond adding a label?
Link helper and error text with aria-describedby, mark invalid fields with aria-invalid="true", and use the right type and autocomplete values so browsers and password managers can help. Group related controls, such as radio buttons, in a <fieldset> with a <legend>. Announce errors with a live region or by moving focus to the first error, and never rely on color alone.
<label for="pw">Password</label>
<input id="pw" type="password" autocomplete="new-password" aria-describedby="pw-hint">
<p id="pw-hint">At least 12 characters.</p>
38. What does the `autocomplete` attribute do and why does it matter?
autocomplete tells the browser what kind of data a field expects, using tokens such as email, given-name, postal-code, one-time-code or current-password. This lets browsers and password managers fill forms correctly and quickly. It is also a WCAG requirement for fields collecting personal information. Setting autocomplete="off" is often ignored for login fields by modern browsers.
39. How do you prevent clickjacking and XSS from the HTML side?
For clickjacking, forbid framing with the CSP frame-ancestors directive or X-Frame-Options. For XSS, never insert untrusted input with innerHTML; use textContent or sanitize it, and apply a Content Security Policy that blocks inline scripts. Escape output on the server by context. Also add rel="noopener" to untrusted links and sandbox to untrusted iframes.
<meta http-equiv="Content-Security-Policy" content="script-src 'self'">
40. What is Subresource Integrity (SRI) and when do you use it?
Subresource Integrity lets the browser verify that a file fetched from a CDN has not been altered. You add an integrity attribute containing a hash of the expected file, and the browser refuses to run the resource if the hash does not match. It needs crossorigin="anonymous" for cross-origin files. Use it for third-party scripts and stylesheets, but not for ones that change often.
<script src="https://cdn.example.com/lib.js"
integrity="sha384-BASE64HASH" crossorigin="anonymous"></script>
41. What is the critical rendering path, and how does HTML affect it?
The critical rendering path is the sequence the browser follows to turn HTML, CSS and JavaScript into pixels: build the DOM, build the CSSOM, combine them into a render tree, then lay out and paint. CSS blocks rendering and synchronous scripts block parsing. To speed it up, inline critical CSS, load other CSS without blocking, use defer for scripts, and keep the DOM small.
42. How would you improve Core Web Vitals such as LCP, CLS and INP using HTML?
For LCP, preload or set fetchpriority="high" on the hero image and avoid lazy-loading it. For CLS, set width and height on images, iframes and ads so space is reserved. For INP, keep the DOM small and defer heavy scripts so the main thread stays responsive. Also compress images and use modern formats like WebP or AVIF.
<img src="hero.avif" width="1200" height="600" fetchpriority="high" alt="Hero">
43. What are `rel="canonical"`, `hreflang` and `rel="nofollow"` used for?
rel="canonical" tells search engines which URL is the preferred version of duplicate or similar pages. hreflang links alternate language or regional versions of a page so users get the right one. rel="nofollow" hints that a link should not pass ranking credit, and ugc and sponsored are more specific variants for user content and paid links.
<link rel="canonical" href="https://example.com/page">
<link rel="alternate" hreflang="es" href="https://example.com/es/page">
44. What is the difference between `<link>` and `@import` for loading CSS?
<link rel="stylesheet"> lets the browser discover and download the stylesheet while parsing HTML, and several can load in parallel. @import inside a CSS file is only found after that file is downloaded, creating a chain of sequential requests that delays rendering. For performance, prefer <link> tags or bundle the CSS, and avoid @import in production.
45. How do the `<form>` attributes `enctype` and `target` matter for file uploads?
To upload files you need method="post" and enctype="multipart/form-data", because the default application/x-www-form-urlencoded sends only file names, not contents. Add accept on the file input to hint at allowed types and multiple for several files. The accept filter is only a convenience, so validate the file type and size on the server.
<form method="post" enctype="multipart/form-data">
<input type="file" name="photo" accept="image/*">
<button>Upload</button>
</form>
46. How would you structure heading levels on a page, and what mistakes are common?
Use one <h1> describing the page, then <h2> for main sections and <h3> for subsections, never skipping levels just for font size. Headings form the outline that screen reader users navigate by, and search engines read it too. Common mistakes are choosing a heading for its look, using several unrelated <h1> elements, and using bold text instead of a real heading.
47. What is the difference between `<button type="button">`, `type="submit"` and `type="reset"`?
Inside a form, a <button> defaults to type="submit", so a click submits the form even if you only wanted to run JavaScript. Use type="button" for actions that should not submit, such as opening a menu. type="reset" restores all fields to their initial values, which is rarely wanted because it can wipe user input by accident.
48. What are microdata and JSON-LD, and which should you use for structured data?
Both describe content using the schema.org vocabulary so search engines can show rich results. Microdata adds attributes like itemscope and itemprop directly into visible HTML, while JSON-LD places a separate script block with JSON. Google recommends JSON-LD because it is easier to maintain and does not mix with markup. Always make sure the data matches what users actually see.
<script type="application/ld+json">
{ "@context": "https://schema.org", "@type": "Article",
"headline": "HTML Interview Questions" }
</script>
49. What is the difference between `<picture>` with `srcset` and CSS `background-image` for images?
An <img> or <picture> is content: it has alt text, is indexed by search engines, supports srcset, native lazy loading and the browser's preload scanner. A CSS background-image is decoration, has no alt text, and is found later because the browser must parse the CSS first. Use <img> for meaningful images and CSS backgrounds only for decorative ones.
50. How do browsers parse HTML, and what is the difference between the DOM and the HTML source?
The browser tokenizes the HTML bytes and builds the DOM tree incrementally, fixing errors by following the specification. The DOM is the live in-memory tree that JavaScript can change, while the source is just the original text. They can differ: the parser adds missing elements such as <tbody>, repairs bad nesting, and scripts can add or remove nodes. "View source" shows the original, while DevTools shows the DOM.