Basic HTML Interview Questions
Basic HTML Interview Questions
HTML mein logic nahin hota toh fir HTML developer kya karta hai?
(Difference between HTML vs actual programming language)
Ans: HTML ek markup language hai jo web pages ka structure banata hai. Isse browser content ko display karta
hai.
Ans: <!DOCTYPE html> browser ko batata hai ki yeh HTML5 document hai. Yeh rendering mode set karta hai.
Ans:
Ans:
• Tag = <p>
Ans: Block element full width leta hai (e.g. div, h1, p), inline sirf content ki width (span, a)
7. <div> vs <span>?
Ans:
Ans: Jo meaning batate hain + SEO friendly: (header, footer, nav, section, article)
Ans: Special characters ke codes jaise (non-breaking space), < <, & &
Ans: id unique hota hai (ek page me ek), class multiple elements me use ho sakti hai.
Ans:
<button type="submit">Send</button>
</form>
Ans: text, password, email, number, checkbox, radio, date, file, submit, etc.
Ans: Form inputs ko clickable name dena, accessibility improve karta hai.
Ans: placeholder = light hint text, value = actual default filled value.
Ans: Semantic tags (header, footer, nav), audio/video tags, canvas, local storage, geolocation API, etc.
Ans: Web page par multimedia play karne ke liye bina external plugins ke. <source> ke through multiple
formats de sakte hain.
Ans: <canvas> element 2D graphics draw karne ke liye JavaScript ke through use hota hai (like charts/games).
24. Local storage vs Session storage?
Ans: <title>, <meta name="description">, heading tags (h1, h2), <alt> in images, proper semantic sections.
Ans: Image load na ho toh text dikhe, plus accessibility (screen readers), SEO improvement.
Ans: <strong> and <em> have semantic meaning (important, emphasis) while <b> and <i> sirf style dene ke
liye.
Ans: Ek HTML page ke andar doosra web page embed karne ke liye. Eg: YouTube video embed.
Ans:
• Progressive enhancement: basic content sabko dikhe, features advance browsers ko.
• Graceful degradation: pehle advanced banaate, fir older browsers ke liye fallback.
Type Location
Ans: No. HTML document mein sirf ek head tag valid hota hai.
Ans: Accessibility ke liye attributes jaise role="button" jo screen readers ko batate hai element ka purpose.
36. Semantic tags SEO mein kaise help karte?
Ans: Search engines structure samajh paate hain, better indexing hoti hai.
Ans: XHTML XML-based strict version hai HTML ka. Tags properly close karna mandatory, attribute names
lowercase etc.
Ans: Document Object Model – HTML page ka tree structure representation jisko JS se manipulate kar sakte
hain.
Ans: Apne extra data store karne ke liye like <div data-id="123"> – JS se fetch kar sakte ho.
Ans: Custom reusable elements with encapsulated structure using Shadow DOM, templates, custom elements.
Ans: Section = generic group of content. Article = self-contained independent content (blog post, news).
Ans: Responsive images serve karne ke liye based on device width – different sources for different screen sizes.
Ans: Images tab load hon jab viewport mein aaye – <img loading="lazy" ...> improves performance.
Ans: Content type define karta hai server se file ka type – e.g. text/html, image/png, application/json.
Ans: No. HTML specification allow nahi karta form ke andar doosra form.
Ans: type="submit" (form submit), type="reset" (clear form), type="button" (normal button).
Ans:
• defer: script load parallel but run after HTML parsing completed (in order)
Ans: HTML element ko editable bana deta hai – <div contenteditable="true">Some text</div>.
50. SSR vs CSR (HTML point)?
Ans: Server-side rendering: server HTML ready bhejta hai (fast first load). Client-side rendering: browser JS se
HTML banata hai (React apps).
Ans: UTF-8
Ans: Elements that cannot have any child content and do not require a closing tag. Eg: <img>, <br>, <input>
Ans: Content inside <noscript> is shown to users whose browsers do not support JavaScript or have it disabled.
Ans: charset is short syntax in HTML5. http-equiv is older HTML4 way and more verbose. Both set encoding
for document.
Ans:
• <object> is more flexible, can specify fallback and is considered more standard
Ans: It is a part of Web Components that allows encapsulation of HTML structure and styles so they don’t affect
the rest of the page.
Ans: Custom elements are user-defined tags like <my-card></my-card> that behave like real HTML tags using
JS.
Ans: It holds HTML that is not rendered unless activated via JavaScript. Useful for rendering blocks
dynamically.
Ans: Provides multiple image URLs with different device resolutions so the browser selects the best one.
10. What is the difference between HTMLCollection and NodeList?
Ans:
Ans: The sequence of steps the browser takes to convert HTML, CSS, JS to pixels on screen. Optimizing it
makes site faster.
12. Explain what happens if you omit the <tbody> tag in a table.
Ans: Browsers automatically insert <tbody> around table rows for you even if you omit it.
Ans: Browser reads HTML and converts it into a DOM tree structure.
Ans: Delays loading of image until it scrolls into viewport, improving page performance.
15. What’s the difference between Block Formatting Context (BFC) and Stack Context?
Ans: BFC is a layout concept that prevents margin collapsing, Stack Context deals with z-index stacking of
positioned elements.
16. What is the difference between hidden attribute and display: none via CSS?
Ans: Both hide the element visually. But hidden is boolean HTML attribute, can be overridden by CSS, and
accessible to screen readers differently.
Ans: Prevents the opened page from gaining access to the original window via window.opener (security) and
hiding referrer header.
18. What is a Document Type Definition (DTD) and why does HTML5 not need one?
Ans: DTD defines valid structure for SGML-based docs (HTML4). HTML5 is no longer based on SGML so
DTD is not needed, only a simple doctype.
Ans: Browsers create a live interactive DOM, handle scripts, CSS and events. Server-side parsers just read tags
for data or transformation.
Ans: They group form controls and provide a caption, improving accessibility and semantics.
Ans: Represents a specific date/time that can be machine-readable via datetime attribute, improving microdata
and semantic search.
22. Difference between title and aria-label attributes?
Ans:
Ans: You can’t fully — must sanitize content server-side or use textContent instead of innerHTML.
Ans: Content placed between tags (like <video>fallback text</video>) that shows if browser doesn't support
that tag.
Ans: It displays a progress bar showing completion progress of a task (e.g. 0–100%).
Ans:
• <meter> = represents a known numeric measure within a range (like score, disk usage).
Ans: Way of embedding machine-readable metadata into HTML using attributes like itemscope, itemtype,
itemprop.
Ans: Used to create collapsible content; <summary> is always visible and acts like a toggle.
Ans: A feature allowing draggable elements using attributes like draggable="true" plus JS events (dragstart,
drop).
Ans: Browser automatically inserts it based on parsing rules. But it should be there for standards compliance.
Ans:
Ans: Allows the browser to access user location by using navigator.geolocation methods (getCurrentPosition).
34. What is the main difference between HTML4 and HTML5 in handling content?
Ans: HTML5 is not based on SGML, provides semantic tags, multimedia support, offline storage, web workers,
etc.
Ans: Old browsers don’t support placeholder, so developers use JS or CSS to mimic placeholder behavior.
Ans: Sets a base URL for all relative URLs in the document. Only one <base> tag allowed.
Ans: Restricts iframe content (disables scripts, prevents forms) unless specific permissions are added
• Normal (blocking)
Ans: It was used in Application Cache to allow offline access. It’s deprecated and replaced by Service Workers.
42. What is a “cookie-less domain” and why used for static assets?
Ans: Domains that do not send cookies in HTTP headers – reduces request size for images/css/js and improves
performance.
Ans: Deprecated — all styling should be done using CSS, not with HTML tags.
44. What is data- attribute good for?
Ans: Attach custom data to HTML elements that can be accessed via JavaScript (no effect on layout).
45. Explain what ‘preload’ and ‘prefetch’ links do (<link rel="preload"> / <link rel="prefetch">).
• preload: loads resource early (high priority) needed for current page
• prefetch: loads resource likely needed for future navigation (low priorit
Ans: Defines tab order for keyboard navigation or makes non-focusable elements focusable.
Ans: Helps screen readers understand element purpose (e.g. role="button"). Useful when using custom
elements.
Ans: colspan extends cell across multiple columns, rowspan across multiple rows.
Ans: To denote abbreviations or acronyms; helps accessibility/SEO by giving full meaning via title attr.
50. What is Content Security Policy (CSP) and how can it be embedded in HTML?
Ans: Security layer to prevent XSS attacks. Can be added via <meta http-equiv="Content-Security-Policy"
content="..." > in document head.
Ans:
• Repaint: Only visual appearance changes (color, background), layout same – faster.
Ans: Allows the browser to make early network connections (DNS, TLS handshake) to external domains before
actual requests, improving load speed.
53. What can happen if you omit closing tags like </li> or </p>?
Ans: Browsers usually auto-close them during parsing (HTML is forgiving), but structure may break or
unexpected layout can happen.
Ans: It allows you to provide inline HTML content directly inside the iframe without external file.
56. Why is it bad to put inline JavaScript inside href="#"?
Ans: It can cause page scroll-to-top, is bad for accessibility, and mixes behavior with markup.
Ans: Lightweight DOM container used for building a portion of DOM in memory, then inserting at once –
prevents multiple reflows.
Ans: External CSS and script tags pause HTML parsing until resource is downloaded & parsed — blocking and
slowing page load.
Ans: DOM is structure of HTML nodes, Render Tree is DOM + CSS styling only nodes that will be drawn
(excluding display:none).
60. How can you detect browser support for a HTML feature without JS?
61. What is the HTTP 'Accept' header and why HTML matters?
Ans: Browser sends Accept: text/html telling server what content type it can handle; server sends correct HTML
MIME type.
Ans: Tells search engines the preferred URL for a page to avoid duplicate content problems.
Property Description
Ans: HTML4 allowed 1 main <h1>; HTML5 allows multiple <h1> per section. Still best practice to use logical
heading hierarchy.
Ans: Browser parses ahead (speculates) to find resources like CSS/JS while still building DOM – for speed.
Ans: User-Agent sniffing is unreliable. Feature detection checks if a capability exists (modern & safer
approach)
Ans: data-* is custom attribute to store data. CSS content is pseudo-element content only for display.
Ans: Browsers treat newline/spaces in HTML as actual space between inline-block elements → adds a 4px or
gap.
Ans: JavaScript running in background threads separate from main UI thread, but part of HTML5 spec, not
HTML markup tag.
72. What is difference between <label for="id"> vs wrapping input inside label?
Ans: Both link the text to input. for= works for inputs outside label. Wrapping works without id attribute.
Ans:
Ans: Browser guessing content type if header missing → can cause security issues. Prevent by X-Content-Type-
Options: nosniff header.
Ans: Loads JS as ES6 module, supports import/export syntax, deferred by default, and scoped.
76. What happens if you put block-level elements inside <p> tags?
Ans: It’s invalid HTML; browser will auto-close <p> before block-level element and unexpected layout may
occur.
Ans: A snippet of code (usually JS) that replicates the functionality of a newer HTML/JS feature on older
browsers not supporting it.
Ans:
Ans: Browser renders page in backward-compatible mode (like old IE behavior) due to missing/incorrect
doctype.
Ans: Deprecated proposal; intended to limit style to the parent element, but now replaced by Shadow DOM.
Ans: Only one Content-Type header applies. Multiple meta tags can conflict — last one wins.
Ans: New HTML element for modal dialogs and pop-ups. Requires JS .show() and .close() methods.
Ans: Preventing a page from being embedded in an iframe using headers like X-Frame-Options, prevents
clickjacking.
Ans:
Ans: Browser avoids autofilling saved info, but some browsers ignore this for certain fields like
username/email.
Ans: A random token to allow only specific inline scripts under CSP to run — prevents XSS.
Ans: <figure> wraps content like an image or chart. <figcaption> is the caption or label for that figure.
Ans: Because new page can access window.opener and potentially redirect or manipulate original page →
security risk.
89. What is the difference between <small> and CSS .small class usage?
Ans: <small> has semantic meaning: represents fine print or legal notes. .small is just styling.
Ans: Inline SVG (<svg>...</svg>) is part of DOM, can be styled by CSS. Using <img src="file.svg"> treats it
like image, not part of DOM.
91. What is 'CORS' and how it relates to HTML?
Ans: Cross-Origin Resource Sharing — browser security policy to restrict requests between different domains
enforced in HTML requests for APIs.
Ans: Makes all links open in new tab by default unless overridden individually.
Ans: The whole innerHTML content re-parses and reflows → expensive, potential DOM state loss (event
listeners lost).
Ans: Type of XSS where user inputs HTML tags that get rendered, compromising layout or structure.
Ans: For East Asian typography, <rt> is text of pronunciation. <rp> provides parentheses fallback if browser
doesn’t support ruby.
Ans: Hint to browser that element is likely to change (transform, opacity) so it can optimize; misuse can cause
memory issues.
Ans: Inline only essential CSS needed for above-the-fold content in <head> to render fast before loading full
stylesheet.
Ans: <noscript> is standard; conditional comments were IE-only feature used to load code/styles only in older
IE versions.
100. What is difference between data: URLs and normal URLs in an <img> tag?
Ans: data: URLs embed image bytes directly in HTML (Base64). Normal URLs fetch external file. Data URLs
increase HTML size but reduce extra HTTP requests.
Ans: HTML streaming sends parts of the HTML document to the browser while the server is still generating
later parts, improving perceived performance.
2. What is the difference between HTML templates and JSX templates?
Ans: HTML templates are static and parsed by the browser. JSX is a syntax extension for JS compiled into
React.createElement.
Ans: Hydration is attaching JS behavior/events to server-rendered HTML to make it interactive on the client
side.
Ans: Subresource Integrity (SRI) allows browser to verify resource via hash to prevent tampered external
resources.
Ans: It suggests a line break opportunity for the browser during word wrapping (word break hint).
Ans: <select> is a dropdown list; <datalist> is for autocomplete suggestions while still allowing free typing.
Ans: Conventions using class names like h-card, h-event to embed structured data that machines can parse
without extra APIs.
Ans: It blocks rendering and can overwrite full document if used after page load.
Ans: Yes in HTML5, a button can contain other elements like <div> or <span>.
Ans: It whitelists only those two restrictions: allows JS and same-origin behavior, but still blocks others like
forms or popups.
Ans: insertAdjacentHTML inserts HTML without re-parsing entire element and without removing existing
event listeners.
Ans: HTML injection modifies page structure or layout; JS injection allows malicious script execution—XSS is
form of JS injection.
14. Can we use async and defer together on the same script tag?
Ans: If both are present, async is ignored and script acts like defer.
15. What is HTML Document.readyState?
Ans: A property (loading, interactive, complete) showing current parsing status of the document.
16. Difference between incremental DOM and virtual DOM in frameworks context?
Ans: Incremental DOM (Google’s approach) patches DOM as needed. Virtual DOM re-renders diff of entire
virtual structure.
Ans: Copying the structure of a legitimate page to trick users phish-style, often combined with HTML/CSS
mimicry.
Ans: Hides content from assistive technologies (screen readers), even if visible visually.
Ans: Delivering HTML in chunks combined with chunked transfer encoding, improving first contentful paint.
Ans: Used for context menus; <menuitem> is deprecated but <menu> can be used with browser context menu
features.
Ans: scope on <th> Uplifts header to row or column; headers attribute on <td> explicitly associates data cell
with header id for accessibility.
Ans: Preconnect establishes connection. Prefetch downloads resource for future navigation.
Ans: Using <meta http-equiv="X-Content-Type-Options" content="nosniff"> to tell browser not to guess MIME
type.
Ans: history.scrollRestoration = 'manual' or 'auto' controls restoring scroll position when navigating back.
Ans: Instructs the browser to perform DNS lookup for an external domain early, even if no resources have been
requested yet.
Ans: Affordance means visual cue of how to interact: e.g <button> clearly clickable. Semantic HTML elements
create better affordance and accessibility.
28. What are HTML parsing quirks that involve <tbody>, <thead>, and <tfoot>?
Ans: Browsers automatically reorder table sections even if written out-of-order, and insert <tbody> if not
present.
Ans: Regions where updates should be announced by screen readers automatically: e.g. aria-live="polite" or
assertive.
Ans: <picture> is for responsive images (file-level). CSS media is for styling; cannot swap image file logic as
efficiently.
Ans: <main> is unique content of page (only one allowed). <section> can be multiple content groups.
Ans: Extract minimal CSS required to render above-the-fold and inline it in HTML <head> to improve
performance before loading full CSS.
Ans: Multiple spaces, tabs, newlines in HTML text nodes are collapsed into a single space unless using <pre>
or CSS white-space.
Ans: new-password indicates that the field expects a new password and suggests new strong password; off
might get ignored.
Ans: Required when fetching resources from other origins to allow CORS requests with credentials or without
(anonymous).
Ans: Official spec to define your own HTML tags using class extends HTMLElement +
window.customElements.define().
Ans: Embeds HTML without making external requests, reducing XSS risk and eliminating network
dependency.
Ans: Using id or name attribute inside an element to allow in-page navigation: <a href="#section1">Go</a>.
39. Explain the difference between HTML comments and conditional comments in IE.
Ans: HTML comments are universal. Conditional comments like <!--[if IE]> were IE-specific for legacy
browser hacks.
40. How can you prevent form auto-submission on Enter key?
Ans: Add onsubmit handler that returns false, or use <button type="button"> for custom buttons, or JS
event.preventDefault().
Ans: HTML imports (deprecated) loaded other HTML into page via browser; server-side includes embed
partials before serving HTML.
Ans: <s> = content no longer accurate but not deleted; <del> = removed text with history; <strike> is
deprecated.
Ans: Use images, or libraries like MathJax which parse custom notation and render via JS/CSS.
Ans: device-width matches device screen width; content-width considers content width which may not align
with screen.
Ans: contenteditable allows any element to become editable rich text via browser; <textarea> is plain text input
in form.
Ans: Groups related elements like form options into a single accessible group — helpful for screen readers.
47. Explain the difference between HTML Tags vs Components (in modern JS frameworks).Ans: HTML
tag is static markup. Component is reusable UI unit containing HTML + behavior + state defined in JS.
Ans: Boolean attribute that tells browser to highlight spelling mistakes in editable content.
Ans: Actually “POUR” model is correct (Perceivable, Operable, Understandable, Robust) – principles for
accessible HTML.
Ans: Overuse of <div> without semantic meaning leads to unstructured, hard-to-maintain HTML code — poor
semantics and accessibility.