HTML Interview Questions
This article covers the most frequently asked HTML and HTML5 questions asked in interviews.
Before starting with the interview questions on HTML Language, let’s first go through HTML, what is HTML, the career opportunities it provides, etc.
What is HTML?
HTML stands for HyperText Markup Language. It is a standard text formatting language used for developing web pages released in 1993. HTML is a language that is interpreted by the browser and it tells the browser what to display and how to display.
HTML is an important language to learn if anyone wants to work in the web development domain [Web designers, Web Developers]. HTML alone is not sufficient for a web developer because HTML only defines the structure of the data that will be rendered on the browser in a webpage, to make it visually appealing and to make it functional, we will need to use CSS and Javascript respectively.
The latest version of HTML is HTML5. There are two main components in HTML language, Tags and Attributes. The below image shows some basic HTML tags and attributes.

HTML Interview Questions and Answers
1. What are the different kinds of Doctypes available?
The three kinds of Doctypes which are available:
- Strict Doctype
- Transitional Doctype
- Frameset Doctype
2. How to specify the link in HTML and explain the target attribute?
HTML provides a hyperlink - <a> tag to specify the links in a webpage. The ‘href’ attribute is used to specify the link and the ‘target’ attribute is used to specify, where do we want to open the linked document. The ‘target’ attribute can have the following values:
- _self: This is a default value. It opens the document in the same window or tab as it was clicked.
- _blank: It opens the document in a new window or tab.
- _parent: It opens the document in a parent frame.
- _top: It opens the document in a full-body window.
4. In how many ways you can display HTML elements?
- inline: Using this we can display any block-level element as an inline element. The height and width attribute values of the element will not affect.
- block: using this, we can display any inline element as a block-level element.
- inline-block: This property is similar to inline, except by using the display as inline-block, we can actually format the element using height and width values.
- flex: It displays the container and element as a flexible structure. It follows flexbox property.
- inline-flex: It displays the flex container as an inline element while its content follows the flexbox properties.
- grid: It displays the HTML elements as a grid container.
- none: Using this property we can hide the HTML element.
Below are some of the display types which are rarely used:
- table
- inline-table
- table-cell
- table-column
- table-row
- inline-grid
- list-item
- inherit
- initial
- table-caption
5. In how many ways can we position an HTML element? Or what are the permissible values of the position attribute?
There are mainly 7 values of position attribute that can be used to position an HTML element:
- static: Default value. Here the element is positioned according to the normal flow of the document.
- absolute: Here the element is positioned relative to its parent element. The final position is determined by the values of left, right, top, bottom.
- fixed: This is similar to absolute except here the elements are positioned relative to the <html> element.
- relative: Here the element is positioned according to the normal flow of the document and positioned relative to its original/ normal position.
- initial: This resets the property to its default value.
- inherit: Here the element inherits or takes the property of its parent.
6. Is it possible to change an inline element into a block level element?
Yes, it is possible using the “display” property with its value as “block”, to change the inline element into a block-level element.
7. How can we club two or more rows or columns into a single row or column in an HTML table?
HTML provides two table attributes “rowspan” and “colspan” to make a cell span to multiple rows and columns respectively.
8. How is Cell Padding different from Cell Spacing?
Cell Spacing is the space or gap between two consecutive cells. Whereas, Cell Padding is the space or gap between the text/ content of the cell and the edge/ border of the cell. Please refer to the above figure example to find the difference.
9. Can we display a web page inside a web page or Is nesting of webpages possible?
Yes, we can display a web page inside another HTML web page. HTML provides a tag <iframe> using which we can achieve this functionality.
<iframe src=”url of the web page to embed” />
10. What is the significance of <head> and <body> tag in HTML?
<head> tag provides the information about the document. It should always be enclosed in the <html> tag. This tag contains the metadata about the webpage and the tags which are enclosed by head tag like <link>, <meta>, <style>, <script>, etc. are not displayed on the web page. Also, there can be only 1 <head> tag in the entire Html document and will always be before the <body> tag.
<body> tag defines the body of the HTML document. It should always be enclosed in the <html> tag. All the contents which needs to be displayed on the web page like images, text, audio, video, contents, using elements like <p>, <img>, <audio>, <heading>, <video>, <div>, etc. will always be enclosed by the <body> tag. Also, there can be only 1 body element in an HTML document and will always be after the <head> tag.
11. What is the difference between <strong>, <b> tags and <em>, <i> tags?
The effect on a normal webpage of the tags <strong>, <b> and <em>, <i> is the same. <b> and <i> tags stands for bold and italic. These two tags only apply font styling and bold tag <b>, just adds more ink to the text, these tags don't say anything about the text.
Whereas, <strong> and <em> tags represent that the span of text is of strong importance or more importance and emphatic stress respectively than the rest of the text. These tags have semantic meaning.
12. Please explain how to indicate the character set being used by a document in HTML?
The character set is defined in <meta> tag inside <head> element.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
...
...
</head>
...
</html>
13. In how many ways can we specify the CSS styles for the HTML element?
There are three ways in which we can specify the styles for HTML elements:
- Inline: Here we use the ‘style’ attribute inside the HTML element.
- Internal: Here we use the <style> tag inside the <head> tag. To apply the style we bind the elements using ‘id’ or ‘class’ attributes.
- External: Here we use the <link> tag inside <head> tag to reference the CSS file into our HTML code. Again the binding between elements and styles is done using ‘id’ or ‘class’ attributes.

14. What are the various formatting tags in HTML?
HTML has various formatting tags:
- <b> - makes text bold
- <i> - makes text italic
- <em> - makes text italic but with added semantics importance
- <big> - increases the font size of the text by one unit
- <small> - decreases the font size of the text by one unit
- <sub> - makes the text a subscript
- <sup> - makes the text a superscript
- <del> - displays as strike out text
- <strong> - marks the text as important
- <mark> - highlights the text
- <ins> - displays as added text
15. How to optimize website assets loading?
To optimize website load time we need to optimize its asset loading and for that:
- CDN hosting - A CDN or content delivery network is geographically distributed servers to help reduce latency.
- File compression - This is a method that helps to reduce the size of an asset to reduce the data transfer
- File concatenation - This reduces the number of HTTP calls
- Minify scripts - This reduces the overall file size of js and CSS files
- Parallel downloads - Hosting assets in multiple subdomains can help to bypass the download limit of 6 assets per domain of all modern browsers. This can be configured but most general users never modify these settings.
- Lazy Loading - Instead of loading all the assets at once, the non-critical assets can be loaded on a need basis.
16. Describe HTML layout structure.
Every web page has different components to display the intended content and a specific UI. But still, there are few things which are templated and are globally accepted way to structure the web page, such as:
- <header>: Stores the starting information about the web page.
- <footer>: Represents the last section of the page.
- <nav>: The navigation menu of the HTML page.
- <article>: It is a set of information.
- <section>: It is used inside the article block to define the basic structure of a page.
- <aside>: Sidebar content of the page.
17. Define multipart form data?
Multipart form data is one of the values of the enctype attribute. It is used to send the file data to the server-side for processing. The other valid values of the enctype attribute are text/plain and application/x-www-form-urlencoded.
18. What is the difference between the ‘id’ attribute and the ‘class’ attribute of HTML elements?
Multiple elements in HTML can have the same class value, whereas a value of id attribute of one element cannot be associated with another HTML element.
19. What is the ‘class’ attribute in HTML?
The class attribute is used to specify the class name for an HTML element. Multiple elements in HTML can have the same class value. Also, it is mainly used to associate the styles written in the stylesheet with the HTML elements.
20. What are different types of lists in HTML?

21. What are HTML Entities?
In HTML some characters are reserved like ‘<’, ‘>’, ‘/’, etc. To use these characters in our webpage we need to use the character entities called HTML Entities. Below are a few mapping between the reserved character and its respective entity character to be used.
| Character | Entity Name | Entity Number |
|---|---|---|
| < | < | < |
| > | > | > |
| & | & | & |
| (non-breaking space) Eg. 10 PM | Eg. <p>10  PM</p> |   |
22. What is the advantage of collapsing white space?
In HTML, a blank sequence of whitespace characters is treated as a single space character, Because the browser collapses multiple spaces into a single space character and this helps a developer to indent lines of text without worrying about multiple spaces and maintain readability and understandability of HTML codes.
23. What are void elements in HTML?
HTML elements which do not have closing tags or do not need to be closed are Void elements. For Example <br />, <img />, <hr />, etc.
24. What are tags and attributes in HTML?
Tags are the primary component of the HTML that defines how the content will be structured/ formatted, whereas Attributes are used along with the HTML tags to define the characteristics of the element. For example, <p align=” center”>Interview questions</p>, in this the ‘align’ is the attribute using which we will align the paragraph to show in the center of the view.
25. Are the HTML tags and elements the same thing?
No. HTML elements are defined by a starting tag, may contain some content and a closing tag.For example, <h1>Heading 1</h1> is a HTML element but just <h1> is a starting tag and </h1> is a closing tag.
26. How to handle events in HTML?
HTML allows event trigger actions in browsers using javascript or JQuery. There are a lot of events like ‘onclick’, ‘ondrag’, ‘onchange’, etc.
<!DOCTYPE html>
<html>
<body style="padding-top:50px">
<h3 id="event_demo">0</h3>
<input type="button" onclick="myFunction()" value="Click Me" />
<input type="reset" onclick="reset()" value="Reset" />
</body>
<script>
function myFunction() {
var value = document.getElementById("event_demo").innerHTML
value = parseInt(value) + 1;
document.getElementById("event_demo").innerHTML = value;
}
function reset() {
document.getElementById("event_demo").innerHTML = 0;
}
</script>
</html>
27. What are forms and how to create forms in HTML?
The HTML form is used to collect the user inputs. HTML provides a <form> tag to create forms. To take input from the user we use the <input> tag inside the form so that all collected user data can be sent to the server for processing. There are different input types like ‘button’, ‘checkbox’, ‘number’, ‘text’, ‘password’, ‘submit’ etc.
<form action="/submit_data.php">
<label>Enter your name: </label>
<input type="text" name="name" />
<label>Enter Mobile number </label>
<input type="number" name="mobile_no"/>
<input type="submit" value="Submit">
</form>
28. When to use scripts in the head and when to use scripts in the body?
If the scripts contain some event-triggered functions or jquery library then we should use them in the head section. If the script writes the content on the page or is not inside a function then it should be placed inside the body section at the bottom. In short, follow below three points:
- Place library scripts or event scripts in the head section.
- Place normal scripts that do not write anything on the page, in the head section until there is any performance issue.
- Place scripts that render something on the web page at the bottom of the body section.
29. How to include javascript code in HTML?
HTML provides a <script> tag using which we can run the javascript code and make our HTML page more dynamic.
<!DOCTYPE html>
<html>
<body>
<h1>
<span>This is a demo for </span>
<u><span id="demo"></span></u>
</h1>
<script>
document.getElementById("demo").innerHTML = "script Tag"
</script>
</body>
</html>
30. Difference between link tag <link> and anchor tag <a>?
The anchor tag <a> is used to create a hyperlink to another webpage or to a certain part of the webpage and these links are clickable, whereas, link tag <link> defines a link between a document and an external resource and these are not clickable.
HTML5 Interview Questions
1. Explain HTML5 Graphics.
HTML5 supports two kinds of graphics:
- Canvas - It is like drawing on a whitepaper or a blank webpage. We can add different graphic designs on web pages with available methods for drawing various geometrical shapes.
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<canvas width="300" height="100" style="border:2px solid;"></canvas>
</body>
</html>- SVG - Scalable Vector Graphics are used mostly for diagrams or icons. It follows the XML format.
<!DOCTYPE html>
<html>
<body>
<svg width="400" height="110">
<rect width="300" height="100" style="fill:#FFF;stroke-width:2;stroke:#000" />
</svg>
</body>
</html>Both of the above examples produce this output and represent two different approaches provided by HTML5 to implement graphical aspects in the webpage.

2. What is new about the relationship between the <header> and <h1> tags in HTML5?
As HTML5 was all about better semantics and arrangements of the tags and elements, the <header> tag specifies the header section of the webpage. Unlike in previous version there was one <h1> element for the entire webpage, now this is the header for one section such as <article> or <section>. According to the HTML5 specification, each <header> element must at least have one <h1> tag.
3. Explain new input types provided by HTML5 for forms?
Following are the significant new data types offered by HTML5:
- Date - Only select date by using type = "date"
- Week - Pick a week by using type = "week"
- Month - Only select month by using type = "month"
- Time - Only select time by using type = "time".
- Datetime - Combination of date and time by using type = "datetime"
- Datetime-local - Combination of date and time by using type = "datetime-local." but ignoring the timezone
- Color - Accepts multiple colors using type = "color"
- Email - Accepts one or more email addresses using type = "email"
- Number - Accepts a numerical value with additional checks like min and max using type = "number"
- Search - Allows searching queries by inputting text using type = "search"
- Tel - Allows different phone numbers by using type = "tel"
- Placeholder - To display a short hint in the input fields before entering a value using type = "placeholder"
- Range - Accepts a numerical value within a specific range using type = "range"
- Url - Accepts a web address using type = "url”
<form>
<div>
<label>Date:</label>
<input type="date" id="date" />
<br>
<label>Week:</label>
<input type="week" id="week" />
<br>
<label>Month:</label>
<input type="month" id="month" />
<br>
<label>Time:</label>
<input type="time" id="time" />
<br>
<label>Datetime:</label>
<input type="datetime" id="datetime" />
<br>
<label>Datetime Local:</label>
<input type="datetime-local" id="datetime-local" />
<br>
<label>Color:</label>
<input type="color" id="color"/>
<br>
<label>Email:</label>
<input type="email" id="email" placeholder="email address" />
<br>
<label>Number:</label>
<input type="number" id="number" />
<br>
<label>Search:</label>
<input type="search" id="search" />
<br>
<label>Phone:</label>
<input type="tel" id="phone" placeholder="Phone Number" pattern="\d{10}$" />
<br>
<label>Range:</label>
<input type="range" id="range" />
<br>
<label>URL:</label>
<input type="url" id="url"/>
</div>
</form>
4. What are the New tags in Media Elements in HTML5?
- <audio> - Used for sounds, audio streams, or music, embed audio content without any additional plug-in.
- <video> - Used for video streams, embed video content etc.
- <source> - Used for multiple media resources in media elements, such as audio, video, etc.
- <embed> - Used for an external application or embedded content.
- <track> - Used for subtitles in the media elements such as video or audio.
<label>
Video:
</label>
<video width="320" height="240" controls>
<source src="video.mp4" type="video/mp4">
<track src="subtitles.vtt" kind="subtitles" srclang="en" label="English">
</video>
<br>
<label>
Embed:
</label>
<embed type="video/webm" src="https://www.youtube.com/embed/MpoE6s2psCw" width="400" height="300">
<br>
<label>
Audio:
</label>
<audio controls>
<source src="audio.mp3" type="audio/mpeg">
</audio>
5. Why do you think the addition of drag-and-drop functionality in HTML5 is important? How will you make an image draggable in HTML5?
The drag and drop functionality is a very intuitive way to select local files. This is similar to what most of the OS have copy functionality thus making it very easy for the user to comprehend. Before the native drag and drop API, this was achievable by writing complex Javascript programming or external frameworks like jQuery.
To enable this functionality there is a draggable attribute in the <img> tag and need to set ondrop and ondragover attribute to an eventhandler available in scripts.
<!DOCTYPE HTML>
<html>
<head>
<script>
function allowDrop(ev) {
ev.preventDefault();
}
function drop(ev) {
...
}
</script>
</head>
<body>
...
<div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)" style="border: 1px solid #aaaaaa; width:350px; height: 70px;"></div>
<br>
<img id="drag1" src="img_logo.gif" draggable="true" width="336" height="69">
...
</body>
</html>
6. Why do we need the MathML element in HTML5?
MathML stands for Mathematical Markup Language. It is used for displaying mathematical expressions on web pages. For this <math> tag is used.
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<math>
<mrow>
<mrow>
<msup>
<mi> a </mi>
<mn> 2 </mn>
</msup>
<mo> + </mo>
<msup>
<mi> b </mi>
<mn> 2 </mn>
</msup>
<mo> + </mo>
<mn> 2 </mn>
<mn> a </mn>
<mn> b </mn>
</mrow>
<mo> = </mo>
<mn> 0 </mn>
</mrow>
</math>
</body>
</html>This displays the equation a2 + b2 + 2ab = 0.
7. What are the server-sent events in HTML5?
The events pushed from the webserver to the browsers are called server-sent events. DOM elements can be continuously updated using these events. This has a major advantage over straight-up polling. In polling, there is a lot of overhead since every time it is establishing an HTTP connection and tearing it down whereas, in server-sent events, there is one long-lived HTTP connection. To use a server-sent event, <eventsource> element is used. The src attribute of this element specifies the URL from which sends a data stream having the events.
<eventsource src = "/cgi-bin/myfile.cgi" />
8. What are Web Workers?
These are added to bring parallelism and async capability. It runs in the background to do the computationally expensive tasks without yielding to make the page responsive. It is achieved by starting a separate thread for such tasks. These are not meant to perform UI operations. There are three types of web workers:
- Dedicated Workers - These are workers that are utilized by a single script.
- Shared Workers -These are workers that are utilized by multiple scripts running in different windows, IFrames, etc.
- Service Workers - These act as proxy servers between web applications, the browser, and the network. Mostly used for push notifications and sync APIs.
<p>Count numbers: <output id="result"></output></p>
<button onclick="startWorker()">Start Worker</button>
<button onclick="stopWorker()">Stop Worker</button>
<script>
var w;
function startWorker() {
if(typeof(Worker) !== "undefined") {
if(typeof(w) == "undefined") {
w = new Worker("demo_workers.js");
}
w.onmessage = function(event) {
document.getElementById("result").innerHTML = event.data;
};
}
}
function stopWorker() {
w.terminate();
w = undefined;
}
</script>
9. What is the usage of a novalidate attribute for the form tag that is introduced in HTML5?
Its value is a boolean type that indicates whether or not the data being submitted by the form will be validated beforehand. By making this false, forms can be submitted without validation which helps users to resume later also.
<form action = "" method = "get" novalidate>
Name:<br><input type="name" name="sname"><br>
Doubt:<br><input type="number" name="doubt"><br>
<input type="submit" value="Submit">
</form>
10. What are raster images and vector images?
Raster Images - The raster image is defined by the arrangement of pixels in a grid with exactly what color the pixel should be. Few raster file formats include PNG(.png), JPEG(.jpg), etc.
Vector Images - The vector image is defined using algorithms with shape and path definitions that can be used to render the image on-screen written in a similar markup fashion. The file extension is .svg
11. How to support SVG in old browsers?
To support old browsers instead of defining the resource of svg in src attribute of <img> tag, it should be defined in srcset attribute and in src the fallback png file should be defined.
<img src="circle.png" alt="circle" srcset="circle.svg">
12. What are different approaches to make an image responsive?
- Art direction - Using <picture> element the landscape image fully shown in desktop layout can be zoomed in with the main subject in focus for a portrait layout.
<picture>
<source media="(min-width: 650px)" srcset="img_cup.jpg">
<img src="img_marsh.jpg" style="width:auto;">
</picture>Bigger Screen (>650px)

For any other screen

- Resolution switching - Instead of zoom and crop the images can be scaled accordingly using vector graphics. Also, this can be further optimized to serve different pixel density screens as well.
For example SVG
<svg width="100" height="100">
<circle cx="50" cy="50" r="40"
stroke="green" stroke-width="4" fill="yellow" />
</svg>
13. What is a manifest file in HTML5?
The manifest file is used to list down resources that can be cached. Browsers use this information to make the web page load faster than the first time. There are 3 sections in the manifest file
- CACHE Manifest - Files needs to be cached
- Network - File never to be cached, always need a network connection.
- Fallback - Fallback files in case a page is inaccessible
CACHE MANIFEST
# 2012-06-16 v1.0.0
/style.css
/logo.gif
/main.js
NETWORK:
login.php
FALLBACK:
/html/ /offline.html<!DOCTYPE HTML>
<html manifest="tutorial.appcache">
...
...
</html>
14. What is the Geolocation API in HTML5?
Geolocation API is used to share the physical location of the client with websites. This helps in serving locale-based content and a unique experience to the user, based on their location. This works with a new property of the global navigator object and most of the modern browsers support this.
var geolocation = navigator.geolocation;
15. Write HTML5 code to demonstrate the use of Geolocation API.
<!DOCTYPE html>
<html>
<body>
<p>Click "try it" button to get your coordinates.</p>
<button onclick="getLocation()">Try It</button>
<p id="demo"></p>
<script>
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation functionality is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
</script>
</body>
</html>The above example asks for user permission for accessing the location data via geolocation API and after clicking the button the coordinates of the physical location of the client get displayed.

16. Explain Web Components and it’s usage.
These are used to create reusable custom elements which are very difficult in traditional HTML. It consists of three technologies:
- Custom elements - These are JavaScript APIs that help in defining custom elements and their behavior.
- Shadow DOM - These are JavaScript APIs that attach an encapsulated shadow DOM tree to an element to keep the element’s features private and unaffected by other parts.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>composed and composedPath demo</title>
<script src="main.js" defer></script>
</head>
<body>
<h1><code>composed</code> and <code>composedPath</code> demo</h1>
<open-shadow text="I have an open shadow root"></open-shadow>
<closed-shadow text="I have a closed shadow root"></closed-shadow>
</body>
</html>customElements.define('open-shadow',
class extends HTMLElement {
constructor() {
super();
const pElem = document.createElement('p');
pElem.textContent = this.getAttribute('text');
const shadowRoot = this.attachShadow({mode: 'open'});
shadowRoot.appendChild(pElem);
}
}
);
customElements.define('closed-shadow',
class extends HTMLElement {
constructor() {
super();
const pElem = document.createElement('p');
pElem.textContent = this.getAttribute('text');
const shadowRoot = this.attachShadow({mode: 'closed'});
shadowRoot.appendChild(pElem);
}
}
);
document.querySelector('html').addEventListener('click', e => {
console.log(e.composed);
console.log(e.composedPath());
});
Here 2 custom elements are defined <open-shadow> and <closed-shadow> which takes their text content and inserts them into a shadow DOM as content of a <p> element.
- HTML templates - The markup templates are written using <template> and <slot> elements which can be reused multiple times as the basis of a custom element's structure.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Simple template</title>
<script src="main.js"></script>
</head>
<body>
<h1>Simple template</h1>
<template id="my-paragraph">
<style>
p {
color: white;
background-color: #666;
padding: 5px;
}
</style>
<p><slot name="my-text">My default text</slot></p>
</template>
<my-paragraph>
<span slot="my-text">Let's have some different text!</span>
</my-paragraph>
<my-paragraph>
<ul slot="my-text">
<li>Let's have some different text!</li>
<li>In a list!</li>
</ul>
</my-paragraph>
</body>
</html>customElements.define('my-paragraph',
class extends HTMLElement {
constructor() {
super();
const template = document.getElementById('my-paragraph');
const templateContent = template.content;
this.attachShadow({mode: 'open'}).appendChild(
templateContent.cloneNode(true)
);
}
}
);
const slottedSpan = document.querySelector('my-paragraph span');
console.log(slottedSpan.assignedSlot);
console.log(slottedSpan.slot);
Here we are reusing the <my-paragraph> template.
References:
Additional Resource
- Practice Coding
- Features of HTML
- HTML MCQ
- HTML Books
- HTML Projects
- HTML IDE
- HTML5 Features
- Different types of css
- Top Web Developer Interview Questions
- How To Become Front End Developer
- Difference Between HTML and HTML5
- Difference Between Frontend and Backend
- Difference Between HTML and JavaScript
- Difference Between HTML and XML
- Difference Between HTML and XHTML
- Difference Between HTML and CSS
- View All Technical Interview Questions
17. Is the <datalist> tag and <select> tag same?
No. The <datalist> tag and <select> tag are different. In the case of <select> tag a user will have to choose from a list of options, whereas <datalist> when used along with the <input> tag provides a suggestion that the user selects one of the options given or can enter some entirely different value.

18. Which tag is used for representing the result of a calculation? Explain its attributes.
The <output> tag is used for representing the result of a calculation. It has the following attributes:
- for - It defines the relationship between the elements used in calculation and result.
- form - This is used to define the form the output element belongs to.
- name - The name of the output element.
<form oninput = "result.value=parseInt(n1.value)+parseInt(n2.value)">
<input type = "number" name = "n1" value = "1" /> +
<input type = "number" name = "n2" value = "2" /><br />
The output is: <output name = "result"></output>
</form>The above example looks like

19. What is Microdata in HTML5?
It is used to help extract data for site crawlers and search engines. It is basically a group of name-value pairs. The groups are called items, and each name-value pair is a property. Most of the search engines like Google, Microsoft, Yandex, etc follow schema.org vocabulary to extract this microdata.
<div itemscope itemtype="http://schema.org/SoftwareApplication">
<span itemprop="name">Interviewbit Games</span> -
REQUIRES <span itemprop="operatingSystem">ANDROID</span><br>
<link itemprop="applicationCategory" href="http://schema.org/GameApplication"/>
<div itemprop="aggregateRating" itemscope itemtype="http://schema.org/AggregateRating">
RATING:
<span itemprop="ratingValue">4.6</span> (
<span itemprop="ratingCount">8864</span> ratings )
</div>
<div itemprop="offers" itemscope itemtype="http://schema.org/Offer">
Price: Rs.<span itemprop="price">1.00</span>
<meta itemprop="priceCurrency" content="INR" />
</div>
</div>- itemid – The unique, global identifier of an item.
- itemprop – Used to add properties to an item.
- itemref – Provides a list of element ids with additional properties.
- itemscope – It defines the scope of the itemtype associated with it.
- itemtype – Specifies the URL of the vocabulary that will be used to define itemprop.
The above example will be parsed by Google as

20. Explain the concept of web storage in HTML5.
This web storage helps in storing some of the static data in the local storage of the browser so that we do not need to fetch it from the server every time we need it. There is a size limit based on different browsers. This helps in decreasing the load time and a smooth user experience. There are two types of web storage that are used to store data locally in HTML5:
- Local Storage - This helps in storing data that will be retained even though the user reopens the browser. It is stored for each webapp on different browsers.
- Session Storage - This is used for one session only. After the user closes the browser this gets deleted.
21. What are the significant goals of the HTML5 specification?
These were the target area of the HTML5 specs:
- Introduction of new element tags to better structure the web page such as <header> tag.
- Forming a standard in cross-browser behavior and support for different devices and platforms
- Backward compatible with the older version HTML web pages
- Introduction of basic interactive elements without the dependency of plugins such as <video> tag instead of the flash plugin.
22. What type of audio files can be played using HTML5?
HTML5 supports the following three types of audio file formats:
- Mp3
- WAV
- Ogg
23. Difference between SVG and Canvas HTML5 element?
| SVG | Canvas |
|---|---|
| SVG is a vector based i.e., composed of shapes. | It is Raster based i.e., composed of pixels. |
| SVG works better with a larger surface. | Canvas works better with a smaller surface. |
| SVG can be modified using CSS and scripts. | Canvas can only be modified using scripts. |
| SVG is highly scalable. So we can print at high quality with high resolution. | It is less scalable. |
24. Is drag and drop possible using HTML5 and how?
Yes, in HTML5 we can drag and drop an element. This can be achieved using the drag and drop-related events to be used with the element which we want to drag and drop.
25. What is the difference between <meter> tag and <progress> tag?
<progress> tag should be used when we want to show the completion progress of a task, whereas if we just want a scalar measurement within a known range or fraction value. Also, we can specify multiple extra attributes for <meter> tags like ‘form’, ‘low’, ‘high’, ‘min’, etc.
26. Convert the below data into Tabular format in HTML5?
S.no., Language, Mostly used for
1, HTML, FrontEnd
2, CSS, FrontEnd
3, Python, BackEnd

27. What are Semantic Elements?
Semantic elements are those which describe the particular meaning to the browser and the developer. Elements like <form>, <table>, <article>, <figure>, etc., are semantic elements.
28. Define Image Map?
Image Map lets a developer map/link different parts of images with the different web pages. It can be achieved by the <map> tag in HTML5, using which we can link images with clickable areas.
<img src=”image_url” , usemap=”#workspace” />
<map name=”workspace”>
<area shape=”rect” coords=”34, 44, 270, 350” , href=”xyz.html” />
<area shape=”rect” coords=”10, 120, 250, 360” , href=”xyz.html” />
</map>
29. How to specify the metadata in HTML5?
To specify we can use <meta> tag which is a void tag,i.e., it does not have a closing tag. Some of the attributes used with meta tags are name, content, http-equiv, etc. The below image tells how to specify the metadata.

30. What is the difference between <figure> tag and <img> tag?
The <figure> tag specifies the self-contained content, like diagrams, images, code snippets, etc. <figure> tag is used to semantically organize the contents of an image like image, image caption, etc., whereas the <img> tag is used to embed the picture in the HTML5 document.
31. Inline and block elements in HTML5?
| Inline | Block |
|---|---|
| Inline elements just take up the space that is absolutely necessary for the content and does not start from a new line. Example:- <span>, <a>, <strong>, <img>, <button>, <em>, <select>, <abbr>, <label>, <sub>, <cite>, <abbr>, <script>, <label>, <i>, <input>, <output>, <q>, etc. |
Block elements start on a new line and consume the full width of the page available. Example:- <div>, <p>, <header>, <footer>, <h1>...<h6>, <form>, <table>, <canvas>, <video>, <blockquote>, <pre>, <ul>, <ol>, <figcaption>, <figure>, <hr>, <article>, <section>, etc. |

32. How can we include audio or video in a webpage?
HTML5 provides two tags: <audio> and <video> tags using which we can add the audio or video directly in the webpage.
33. What are some of the advantages of HTML5 over its previous versions?
Some advantages of HTML5 are:-
- It has Multimedia Support.
- It has the capabilities to store offline data using SQL databases and application cache.
- Javascript can be run in the background.
- HTML5 also allows users to draw various shapes like rectangles, circles, triangles, etc.
- Included new Semantic tags and form control tags.
Advanced HTML Interview Questions
1. What are semantic HTML best practices, and why do they matter for accessibility and SEO?
Semantic HTML means using elements that clearly describe their purpose and content, instead of relying on generic containers like <div> and <span> for everything. Elements like <header>, <nav>, <main>, <article>, <section>, <aside>, and <footer> all communicate the role and purpose of their content to the browser, assistive technologies, and search engine crawlers. Writing semantic HTML is not just a stylistic choice; it has a direct, measurable impact on both accessibility and SEO.
From an accessibility pov, screen readers and other assistive technologies rely heavily on semantic markup to help visually impaired users navigate a page. When you use a <nav> element, a screen reader knows to announce it as a navigation landmark, allowing users to jump directly to it. When you use <button> for an interactive control instead of a styled <div>, the browser automatically makes it focusable, keyboard operable, and announces it correctly to assistive tools. Replacing these native elements with generic divs means you have to manually recreate all of that behaviour using ARIA attributes, which is error-prone and far harder to maintain.
So when you look at it from the point of SEO, search engine crawlers parse your HTML to understand the structure and hierarchy of your content. Using a proper <h1> through <h6> heading hierarchy signals which content is most important on the page. Wrapping an article in an <article> tag tells crawlers that the content within is a standalone, indexable piece. Using <figure> and <figcaption> around images helps search engines associate descriptive context with visual content. All of these signals contribute to how well a page ranks and how accurately it is represented in search results.
Here are some key semantic HTML best practices that you can follow:
- Use one
<h1>per page that clearly describes the page's primary topic, and never skip heading levels - always go from<h1>to<h2>to<h3>in order. - Use
<button>for actions and<a>for navigation; never use a<div>or<span>as a clickable element, as they are not natively keyboard accessible. - Always wrap form inputs in
<label>elements, so assistive technologies can correctly associate the label with its control. - Use
<ul>or<ol>for lists rather than manually styling divs to look like one, so screen readers can announce the list and its item count. - Use
<figure>and<figcaption>when pairing images with descriptive text, giving both browsers and crawlers the right context around visual content. - Reach for landmark elements like
<main>,<nav>,<aside>, and<footer>to define page regions, allowing screen reader users to jump between sections efficiently.
It’s always worth checking if a native HTML element already fits what you’re building. If it does, using it gives you accessibility, SEO, and a better code structure without extra effort.
2. When should you use a button vs a (and what breaks if you use the wrong one)?
Always remember this - use <a> when you are navigating somewhere, and use <button> when you are triggering an action.
An anchor tag expects an href and is meant to move the user to a new URL, a section, or a page. A button is meant to do something, submit a form, open a modal, or toggle a component. Using the wrong one breaks more than just semantics. A <button> used for navigation confuses screen readers and breaks right-click to open in a new tab. An <a> used for actions is not keyboard accessible by default and misrepresents the interaction to assistive tools and crawlers alike.
3. What is the purpose of ARIA, and when should you not use ARIA?
ARIA, which stands for Accessible Rich Internet Applications, is a set of attributes defined by the W3C that you can add to HTML elements to improve how assistive technologies like screen readers interpret and interact with your content. It was introduced to handle scenarios where native HTML falls short in describing complex, interactive interfaces. ARIA lets you communicate roles, states, and properties that plain HTML elements cannot convey on their own.
ARIA works across three categories of attributes. Roles define what an element is or does, such as role="dialog", role="tablist", or role="alert", telling the screen reader how to treat that element. States describe the current condition of an element, such as aria-expanded="true" on an accordion or aria-checked="true" on a custom checkbox. Properties provide additional descriptive information, such as aria-label to give an element a name that is not visible on screen, or aria-describedby to associate an element with a longer description elsewhere on the page.
The most important rule in the accessibility community around ARIA is this: no ARIA is better than bad ARIA. ARIA does not fix inaccessible HTML; it only supplements it. Incorrect ARIA usage can actively make an experience worse for screen reader users by overriding correct native semantics with wrong ones.
When you should not use ARIA:
- When a native HTML element already does the job. If you are building a button, use
<button>. If you are building a checkbox, use<input type="checkbox">. Native elements come with built-in roles, keyboard behaviour, and states for free; ARIA should never be used to recreate what already exists natively. - When it is added just for styling hooks. ARIA attributes are purely for assistive technology and have no visual effect. Adding role="button" to a div and then styling it does not make it keyboard accessible; you still need to handle focus and key events manually.
- When the content is purely decorative. Decorative images or icons that add no meaningful information should use alt="" or aria-hidden="true" to hide them from screen readers entirely, rather than adding ARIA labels that create unnecessary noise.
- When it contradicts the element's native role. Applying role="heading" to a
<button>or role="button" to an<h1>confuses assistive technologies and creates an inconsistent, broken experience.
What you must really do here is to always reach for the right native HTML element first, and only layer ARIA on top when you are building something genuinely custom that HTML alone cannot describe.
4. What’s the difference between accessible name sources (aria-label, label, aria-labelledby)?
When a screen reader encounters an interactive element, the first thing it needs to know is what that element is called - this is referred to as its accessible name. There are three primary ways to provide it, and each serves a distinct purpose depending on the situation.
- aria-label is used when you want to give an element a name that is completely invisible on screen. It is written directly as an attribute with the name as its value, making it ideal for icon-only buttons where there is no visible text to rely on. For example, a close button with only an ✕ icon would use aria-label="Close" so screen readers can announce it correctly.
- <label> is the native HTML approach for form inputs and is always the preferred choice when dealing with form controls. It creates a visible, clickable label that is also automatically associated with its input, giving you both accessibility and usability in one element without any extra attributes needed.
- aria-labelledby is used when the name for an element already exists as visible text elsewhere on the page. Instead of duplicating that text, you point to it by referencing the other element's ID. This is particularly useful for dialogs or sections that are titled by a visible heading already present in the DOM, keeping your accessible name and your visual label perfectly in sync without any repetition.
5. How do fieldset and legend improve form accessibility?
When building forms that contain groups of related inputs, such as a set of radio buttons asking for your preferred contact method, or a group of checkboxes for selecting interests, wrapping them in a <fieldset> with a <legend> is the correct semantic approach, and it makes a significant difference for screen reader users.
The <fieldset> element groups related form controls together, telling the browser and assistive technologies that these inputs belong to the same question or topic. The <legend> element sits as the first child inside the fieldset and acts as the shared label for the entire group. When a screen reader focuses on any individual input within the group, it reads the legend text first, followed by that input's own label. So instead of just hearing "Yes - radio button", the user hears "Preferred contact method - Yes - radio button", giving them the full context they need to make a choice.
Without fieldset and legend, grouped inputs lose that shared context entirely. A screen reader would announce each option in isolation, leaving the user to figure out on their own what the group of options actually refers to. This is particularly confusing for radio button groups where no single option makes sense without knowing the question being asked. Using fieldset and legend is one of those small HTML decisions that costs almost nothing to implement but makes the form experience significantly clearer for users relying on assistive technology.
6. What is the difference between autocomplete, inputmode, and pattern, and how do they affect UX?
These three attributes each target a different layer of the input experience, and using them together thoughtfully can make forms feel significantly faster and easier to fill out, especially on mobile devices.
autocomplete tells the browser what kind of data a field expects, so it can offer saved values from the user's profile or previous form submissions. Setting autocomplete="email" or autocomplete="street-address" allows the browser to prefill those fields automatically, saving the user from typing repetitive information. It is a small addition that has an outsized impact on form completion rates.
inputmode controls which keyboard layout appears on mobile when a field is focused, without changing the field's actual data type. Setting inputmode="numeric" on a field brings up a number pad instead of the full keyboard, and inputmode="tel" brings up a dialpad layout. This does not restrict what the user can enter, it simply makes typing faster and less error-prone by surfacing the most relevant keys upfront.
pattern enforces a specific format using a regular expression, and the browser validates against it automatically on form submission. For example, setting pattern="[0-9]{10}" on a phone number field ensures the user enters exactly ten digits. However, pattern alone does not communicate the expected format to the user, so it should always be paired with a visible hint or placeholder explaining what is required, otherwise it creates frustration when the form silently rejects their input.
7. What is the form attribute on inputs/buttons and when is it useful (inputs outside a <form>)?
The form attribute allows an input or button to be associated with a <form> element even when it is not physically nested inside it. You simply set the form attribute on the input or button to match the id of the target form, and the browser treats it as if it were inside that form. This is particularly useful in complex UI layouts where a submit button needs to live in a fixed footer or a separate section of the page, far away from the form itself in the DOM, without needing to restructure the entire HTML layout just to keep them together.
8. What is the difference between readonly and disabled inputs (behavior + form submission)?
Both readonly and disabled prevent a user from editing an input's value, but they behave quite differently beyond that. A readonly input is still focusable, can be tabbed to, and most importantly its value is included when the form is submitted. A disabled input is completely inert as it cannot be focused, cannot be interacted with in any way, and its value is entirely excluded from form submission.
A good way to think about it is that readonly means the user can see and acknowledge the value but not change it, while disabled means the field is simply switched off and irrelevant to the current form submission.
9. What is the difference between <section>, <article>, and <div> in real-world page structure?
The distinction comes down to whether the content has standalone meaning or belongs to a broader context. An <article> is for content that makes complete sense on its own and could be lifted out of the page and published independently, think a blog post, a news story, or a product card. A <section> is for grouping related content that forms a distinct part of a larger whole, like chapters within an article or segments within a landing page, but would not make sense in isolation. A <div> carries no semantic meaning whatsoever and should only be used as a last resort when you need a container purely for styling or layout purposes with no semantic intent behind it.
A real-world blog page illustrates this well. The structure would look something like this:
<main>
<article>
<section></section>
<section></section>
<section></section>
</article>
<div class="sidebar-wrapper">
<aside></aside>
</div>
</main>The <main> holds the page's primary content, and each <article> inside it represents a complete, standalone blog post. Within each article, <section> elements carve it up into distinct parts, the introduction, the body, and the comments. The <div> wrapping the sidebar exists purely to apply a flex or grid layout, carrying no semantic meaning of its own. This layered structure keeps semantics clean, accessibility meaningful, and layout concerns separate.
10. What is the purpose of the <base> tag, and what common routing/linking issues can it cause?
The <base> tag sits inside the <head> of an HTML document and sets a default URL that all relative links and resource paths on the page resolve against. So if you set <base href="https://mysite.com/app/">, every relative link, image source, or script path on the page will be resolved from that base URL rather than the current page's location. This can be useful in certain deployment setups, but it is also a common source of bugs. If your single page application uses client-side routing, the base tag can interfere with how the router resolves paths, causing navigation to point to the wrong URLs. It can also break anchor links, a simple <a href="#section"> will no longer scroll to that section but instead try to navigate to the full base URL with the hash appended.
11. How does the loading="lazy" attribute work for images/iframes, and when should you avoid lazy-loading?
The loading="lazy" attribute tells the browser to defer loading an image or iframe until it is close to entering the viewport as the user scrolls, rather than downloading everything upfront on page load. This reduces the initial page weight significantly and speeds up the time to interactive, especially on image-heavy pages.
However, there are situations where lazy-loading does more harm than good.
Any image that is visible above the fold without scrolling, such as a hero banner or a logo, should never be lazy-loaded, since the browser would unnecessarily delay loading something the user needs to see immediately. Similarly, if your largest contentful paint element is lazy-loaded, it will directly hurt your LCP score, which is a key Core Web Vital metric.
12. What is Subresource Integrity (SRI) and how does the integrity attribute protect external scripts/styles?
Subresource Integrity, or SRI, is a browser security feature that helps you verify external resources like scripts or stylesheets fetched from a CDN or third party have not been tampered with or modified since you last checked them. When you load an external resource, you are inherently trusting that the server serving it has not been compromised. SRI removes that blind trust by letting you specify exactly what the file should contain.
It works by generating a cryptographic hash of the file's contents at the time you add it to your project, and then including that hash in the integrity attribute of your <script> or <link> tag. When the browser fetches the resource, it independently hashes the downloaded file and compares it against the value in your integrity attribute.
If the two match, the file loads normally. If they do not match, meaning the file has been altered in any way, the browser blocks it entirely and throws an error, protecting your users from executing malicious code:
<script
src="https://cdn.example.com/library.js"
integrity="sha384-abc123..."
crossorigin="anonymous">
</script>The crossorigin="anonymous" attribute is required alongside SRI because the browser needs to make a CORS request to be able to inspect and hash the response. Without it, SRI checks cannot be performed at all. SRI is particularly valuable when loading popular libraries from public CDNs, where a supply chain attack could otherwise silently serve compromised files to millions of users.
13. What do rel="noopener noreferrer" do for external links, and why does it matter for security?
When you open an external link using target="_blank", the newly opened tab gets access to the originating page through the window.opener property, meaning a malicious external site could potentially redirect your original page to a phishing URL without the user noticing. Adding rel="noopener" severs that connection entirely, ensuring the new tab has no reference back to your page. rel="noreferrer" goes a step further by also stripping the HTTP referer header from the request, so the destination site cannot see which page the user came from. Both are typically used together on any external link that opens in a new tab, and modern browsers now apply noopener automatically for target="_blank" links, but explicitly declaring both is still considered best practice for full cross-browser security coverage.
14. What is the purpose of the iframe sandbox attribute, and what’s a safe default approach?
When you embed third party content inside an <iframe>, such as a widget, an ad, or a user generated page, you are essentially running untrusted code inside your own page. By default, an iframe has significant access to the parent page and the browser, which creates a real security risk. The sandbox attribute locks down what an embedded iframe is allowed to do, acting as a permission boundary between the embedded content and your page.
In this example, allow-scripts re-enables JavaScript execution inside the iframe, and allow-same-origin allows the iframe to be treated as coming from its own origin rather than a unique opaque one. The safe default approach is to always start with a bare sandbox attribute and add permissions back one by one only when necessary, rather than starting open and trying to lock things down after the fact.
This principle of least privilege keeps your page protected even if the embedded content is compromised.
When you add sandbox to an iframe with no value at all, it applies the strictest possible restrictions, blocking scripts from running, preventing form submissions, blocking popups, disabling plugins, and stopping the iframe from navigating the parent page.
From that locked down baseline, you can then selectively re-enable only the capabilities the embedded content genuinely needs by adding specific permission tokens:
<iframe
src="https://external-widget.com"
sandbox="allow-scripts allow-same-origin">
</iframe>
15. What is the difference between srcdoc and src in iframes, and when is srcdoc useful?
The src attribute points an iframe to an external URL, loading the content from a separate network request. srcdoc, on the other hand, lets you write the iframe's entire HTML content inline as an attribute value, with no network request needed at all. This makes srcdoc particularly useful when you want to render a small, self-contained piece of HTML in an isolated context, such as a live code preview, a sandboxed rich text output, or user generated HTML that you want to display without giving it access to your page's scripts or styles. It also takes precedence over src when both are present, and pairs naturally with the sandbox attribute since the content is already controlled and contained entirely within your own markup.
16. What are preload, prefetch, and preconnect, and when should you use each for performance?
All three are resource hints that you place in the <head> of your HTML document to give the browser advance notice about resources it will need, but they each serve a different purpose and operate at different points in the page lifecycle.
preload is the most urgent of the three. It tells the browser to fetch a specific resource as soon as possible because it will definitely be needed for the current page. It is not a hint, it is an instruction. This makes it ideal for critical assets that the browser would otherwise discover late, such as a hero image, a custom font, or a JavaScript file that is dynamically imported. Without preload, the browser might only discover these resources after parsing through several layers of CSS or JS, causing noticeable delays.
A key thing to remember is that preload must always be paired with an as attribute so the browser knows what type of resource it is fetching and can prioritize it correctly:
<link rel="preload" href="hero.jpg" as="image">
<link rel="preload" href="font.woff2" as="font" crossorigin>prefetch operates at a lower priority and is intended for resources that will be needed on a future navigation rather than the current page. The browser fetches and caches these resources during idle time, so they are ready when the user navigates to the next page.
It is perfect for single page applications where you can predict the user's next likely route, or for loading the next article in a reading flow:
<link rel="prefetch" href="/next-page.js">preconnect does not fetch any resource at all — instead it tells the browser to establish a connection to a third party origin ahead of time, completing the DNS lookup, TCP handshake, and TLS negotiation early so that when a request to that origin is eventually made, the network overhead is already out of the way.
This is particularly valuable for fonts loaded from Google Fonts, analytics scripts, or any API that your page will call shortly after load:
<link rel="preconnect" href="https://fonts.googleapis.com">The right mental model is to think of them in order of urgency, preconnect warms up the connection, preload fetches what you need right now, and prefetch quietly prepares what you will need next.
17. What does the lang attribute affect (screen readers, hyphenation, translation), and where should it be set?
The lang attribute tells the browser, assistive technologies, and external tools what language the content is written in, and its effects are broader than most developers realize. Screen readers use it to select the correct pronunciation engine and accent for text to speech, without it, a French page might be read aloud with entirely wrong English phonetics. Browsers use it to apply the correct hyphenation rules when text wraps across lines. Translation tools like Google Translate also rely on it to detect the source language accurately. It should always be set on the root <html> element as a baseline, and then overridden on any specific element within the page whose content switches to a different language, such as a quoted passage or an internationalized component.
HTML CSS JavaScript Interview Questions (NEW)
1. How do HTML, CSS, and JavaScript work together in the browser rendering pipeline?
When a browser loads a page, it doesn’t render everything instantly. It follows a sequence called the critical rendering path. The interviewers are usually trying to test whether you understand this flow. Now, what you can say is -
It starts with HTML. The browser parses it and builds the DOM, which represents the structure of the page. At the same time, it processes CSS and builds the CSSOM, which contains all the styling rules.
These two are then combined into a Render Tree, which only includes visible elements along with their computed styles. Once that’s ready, the browser moves through:
- Layout - calculating size and position
- Paint - drawing elements on screen
- Compositing - layering everything together
Trust me, you’ll find the process pretty straightforward till here, but be (a little) ready when JavaScript comes next.
So, JavaScript doesn’t directly form part of the rendering steps, but it can block or restart them. If you include a script like this: <script src="app.js"></script>
The browser pauses HTML parsing until the script is downloaded and executed. This is what starts affecting performance on pages, and newer issues start showing up. Even a relatively small script placed in the <head> can delay rendering enough to make the page feel unresponsive at first load.
What works for me to handle this is that browsers provide better loading strategies:
<script src="app.js" defer></script>
<script src="app.js" async></script>- defer makes HTML parsing to continue and runs scripts after the DOM is fully built, preserving execution order
- async runs scripts as soon as they are downloaded, without waiting for parsing or maintaining order
And that is why defer is the safer choice for application code, especially when the script interacts with the DOM. async works well for independent scripts like analytics or ads.
What I’ve also seen quite often is that rendering issues aren’t caused by complex logic, but by how scripts are loaded and when they execute. Once you understand where JavaScript fits into the rendering pipeline, it becomes much easier to reason about why a page feels slow or blocks during load.
2. What is the DOM, and how is it different from the CSSOM?
Here’s what you need to remember - The DOM, or Document Object Model, is a programming interface provided by the browser that represents an HTML document as a structured tree of objects. When a browser receives an HTML file from a server, the raw markup won’t be the only thing being displayed; it parses it and constructs a hierarchical, in-memory tree where every element, attribute, and piece of text becomes a node. Just like when you click a button and new content appears without a reload, that happens because JavaScript is updating the DOM.
But practically, how how much does it make sense?
Let’s suppose a <div> containing a <p> tag becomes a parent node with a child node. This tree structure is what JavaScript interacts with when you use methods like document.getElementById() or querySelector(). Remember that the DOM is dynamic, which means that JavaScript can add, remove, or modify nodes at any time, and the browser will reflect those changes on the screen in real time.
Now that we are done with the first half, it is important that you understand how styling is handled separately. The CSSOM, or CSS Object Model, is a parallel tree structure that the browser builds from all the CSS rules it encounters, whether from external stylesheets, <style> tags, or inline styles. Just like the DOM represents the structure and content of a page, the CSSOM represents all the styling information. It maps every CSS selector to its resolved properties, accounting for specificity, inheritance, and the cascade.
Now you are correct to wonder, “What is the major difference then?” So, basically, the DOM handles structure and content, while the CSSOM handles visual presentation. Neither tree alone is enough to paint pixels on the screen. The browser must combine both into what is called the Render Tree, which only includes visible nodes along with their computed styles.
This render tree is then used for layout calculation and finally painting. So while they're built independently and in parallel, the DOM and CSSOM are deeply interdependent; a page cannot be rendered correctly without both being fully constructed.
So even though they’re built separately, the browser really can’t do much until both are ready.
3. What is the difference between reflow (layout) and repaint, and how do you reduce them?
You know, sometimes when you make small changes to your page, it starts going slower. This is probably why that happens.
Reflow, also referred to as layout, is the process by which the browser recalculates the position, size, and geometry of elements on the page. Whenever something changes that affects the structural layout, such as adding or removing elements from the DOM, changing an element's width or height, modifying font size, or resizing the browser window, the browser needs to go back and recompute how everything fits together. This is an expensive operation because a change to one element can cascade and affect its parent, siblings, and children, forcing large portions of the render tree to be recalculated. That’s why even a small change can end up affecting a much larger portion of the page.
Now not every change is that heavy. When you look at Repaint - It happens when a visual change is made to an element that does not affect its geometry or position. Changing a color, background, border color, or visibility triggers a repaint. The browser already knows where the element sits on the page, so it simply redraws its pixels with the updated style. Repaint is significantly cheaper than reflow, but it is still not free, especially on complex pages.
So compared to reflow, repaint is cheaper, but still not something you want happening repeatedly.
One thing you MUST keep in mind - every reflow triggers a repaint, but not every repaint triggers a reflow.
But, what can be done to reduce them?
Here’s an example for you -
Consider a case where you need to update the width, height, and margin of an element using JavaScript.
If you set up each property one by one:
const box = document.getElementById('box');
box.style.width = '200px';
box.style.height = '150px';
box.style.margin = '20px';Each line forces the browser to recalculate the layout separately and hence end up triggering reflow.
Now what you can do is batch all those changes by toggling a CSS class instead:
.updated-box {
width: 200px;
height: 150px;
margin: 20px;
}js
document.getElementById('box').classList.add('updated-box');This way, all three style changes are applied in a single operation, causing only one reflow instead of three. Batching DOM reads and writes, using CSS classes for style changes, and leveraging properties like transform and opacity, which are handled by the GPU and bypass layout entirely, are among the most effective strategies to keep reflows and repaints to a minimum.
4. Why is event delegation useful, and when should you use it?
This comes up a lot when working with dynamic UIs. Event delegation is a technique in JavaScript where, instead of attaching an event listener to each individual child element, you attach a single event listener to a parent element and let events bubble up to it. This works because of the browser's event bubbling mechanism, where an event triggered on a child element travels up through its ancestors in the DOM tree. The parent listener then checks which child actually triggered the event using the event.target property and responds accordingly. So instead of managing multiple listeners, you handle everything from one place.
So why would you use this approach?
You can find this process useful when you have a large number of similar elements, like a list of products, comments, or notifications, since attaching one listener to the parent is far more memory efficient than attaching hundreds of individual listeners. It also works when elements are dynamically added to the DOM after the page loads, since the listener lives on the parent, any newly added child elements are automatically covered without needing to re-attach listeners every time the DOM changes.
5. What is the difference between event.target and event.currentTarget?
They sound similar, but they point to different things during an event. You’ll notice this especially when using event delegation -
| event.target | event.currentTarget |
|---|---|
| This refers to the exact element the user interacted with, such as the button that was clicked. | This refers to the element that actually has the event listener attached to it, such as a parent div. |
| It can change during event bubbling, always pointing back to the original source of the event. | It remains fixed throughout the event's journey, always reflecting where the listener is registered. |
| It is best used when you want to know precisely what the user clicked or triggered. | It is useful when you want to reference the element that is handling and responding to the event. |
For Eg: clicking a button inside a parent div will make target the button, but currentTarget the div if the listener is on the parent.
Here’s how you can remember it - event.target is where the event started, and event.currentTarget is where it is being handled.
6. How does CSS specificity work, and what is a practical way to avoid specificity wars in large UIs?
CSS specificity is the scoring system browsers use to decide which style rule wins when multiple rules target the same element. Every selector carries a weight, and the rule with the highest total score takes effect. Inline styles carry the highest weight, followed by IDs, then classes, attributes and pseudo-classes, and finally plain element selectors at the lowest level. So a rule targeting #header .nav a will always override one targeting just a, regardless of the order they appear in the stylesheet.
Since every rule carries the same low specificity, overrides become straightforward and intentional rather than a guessing game of selector weight.
Each fix makes the stylesheet heavier and more fragile than before.
So, what you can do to avoid this is follow a naming methodology like BEM, where every component and its variations get their own dedicated flat class names:
.button { background: blue; }.button { background: blue; }
.button--modal { background: green; }
.button--sidebar { background: red; }In large UIs, specificity wars break out when developers keep writing increasingly specific selectors just to override previous ones, making the CSS harder to maintain and predict.
For example, you might start with a simple class to style a button, then keep stacking selectors on top of it just to win the override battle:
.modal .button { background: green; } - here, happens the 1st override
.sidebar .modal .button { background: red; } - and now override again
7. What is the difference between relative units (em, rem, %, vh/vw) and when would you use each?
Relative units scale with a reference point, whereas pixels stay fixed. That’s why they’re commonly used for responsive UIs, with each unit behaving differently based on what it references.
1. em is relative to the font size of the element's own parent. So if a parent has a font size of 16px and you set a child's padding to 1.5em, it computes to 24px. It is useful for component-level scaling where you want child elements to respond to their immediate context, but it can get tricky when elements are deeply nested since the reference keeps shifting.
2. rem is relative to the root element's font size, which is typically 16px in most browsers. Unlike em, it stays consistent no matter how deeply nested an element is. It is the go-to unit for typography and spacing in large UIs because changing the root font size scales everything uniformly.
3. % is relative to the parent element's size, making it ideal for widths and heights in fluid layouts. Setting a container to 50% means it always occupies half of its parent's width, regardless of screen size.
4. vh and vw are relative to the viewport's height and width, respectively, where 1vh equals 1% of the visible screen height. These are perfect for full-screen sections, hero banners, or any element that needs to respond directly to the browser window size rather than its parent container.
8. How do you make a layout responsive using Flexbox/Grid + media queries (high-level approach)?
Building a responsive layout is about combining the right layout tool with breakpoints that adapt it to different screen sizes. The general approach follows a mobile-first mindset, where you design for the smallest screen by default and progressively enhance as the screen gets wider..container {
display: flex;
flex-direction: column; /* mobile: stacked */
}
@media (min-width: 768px) {
.container {
flex-direction: row; /* tablet and above: side by side */
flex-wrap: wrap;
}
}
This keeps the approach clean - Flexbox and Grid handle the fluid behaviour, and media queries handle the intentional structural shifts.
You can refer to these steps, and do keep them in mind -
- Start mobile-first - write your base styles for the smallest screen, with elements stacked vertically and taking full width by default.
- Choose Flexbox or Grid based on your layout need - use Flexbox for one-dimensional layouts like navbars and card rows, and Grid for two-dimensional layouts like full page structures with sidebars and footers.
- Let the layout tool handle fluidity - use flex-wrap in Flexbox or repeat(auto-fit, minmax()) in Grid so elements naturally reflow without needing too many manual breakpoints.
- Add media queries for structural shifts - use breakpoints only when the layout needs a bigger change, like switching from a stacked column to a side-by-side row at a tablet width.
Now for instance, a simple responsive card row using Flexbox would look like this - on mobile the cards stack vertically, and at 768px and above they line up horizontally:
9. What is the difference between inline, block, and inline-block from a UI behavior perspective (when building components)?
When building UI components, these display values control how elements behave in layout. Block elements, like a <div>, always start on a new line and stretch to fill the full width of their container, making them ideal for structural sections. Inline elements, like a <span>, sit within the flow of text and only take up as much width as their content, but they cannot have width or height applied to them. Inline-block sits in the middle; it flows with surrounding content like an inline element, but also respects width, height, and vertical padding like a block element, making it practical for things like styled buttons or navigation items.
10. What are data-* attributes used for, and when should you avoid using them?
Data attributes are a built-in HTML feature that lets you store custom, extra information directly on a DOM element without affecting its visual appearance or semantic meaning. They follow the format data- followed by any name you choose, and some commonly used examples include:
- data-user-id - to store a user's unique identifier
- data-status - to reflect a current state like active or inactive
- data-category - to tag an element with a group or type
- data-action - to define what action a button or element should trigger
JavaScript can then read or modify these values easily through the dataset property, and CSS can even use them as attribute selectors for styling.
They are most useful when you need to pass configuration or metadata to JavaScript without making extra API calls or cluttering your JavaScript with hardcoded values.
You can see this most often in event delegation. Instead of writing separate listeners for each element, you attach one listener to the parent and use data attributes on each child to identify what action to take:
<button data-action="delete" data-id="42">Delete</button>
<button data-action="edit" data-id="42">Edit</button>
parent.addEventListener('click', (e) => {
const { action, id } = e.target.dataset;
});However, you should avoid using them to store data that is sensitive, since data attributes are fully visible in the browser's dev tools and the HTML source. You should also avoid using them as a replacement for a proper application state. If your data is being frequently updated or shared across components, a state management solution is a far more reliable and maintainable approach.
11. What is the difference between defer and async on script loading, and when do you choose each?
Both defer and async allow the browser to download a script without blocking HTML parsing, they mainly differ in when the script gets executed.
- With async, the script runs immediately after it finishes downloading, even if the HTML is not fully parsed yet, making it suitable for independent scripts like analytics or ads that have no dependency on the DOM.
- With defer, the script waits until the entire HTML is parsed before executing, and multiple deferred scripts run in the order they appear. This makes defer the safer and more predictable choice for application scripts that depend on the DOM or on each other.
12. How do you safely update the DOM without causing XSS (e.g., textContent vs innerHTML)?
Cross-Site Scripting, or XSS, is a security vulnerability where malicious scripts are injected into a webpage through user-supplied content and executed in the browser. One of the most common ways this happens in frontend development is through careless use of innerHTML when updating the DOM dynamically.
innerHTML parses whatever string you assign to it as actual HTML markup and renders it accordingly. However, this is exactly what makes it dangerous. If the string contains user-generated content, such as a comment, a username, or a search query, and that content includes something like a <script> tag or an onerror attribute on an image tag, the browser will execute it as live code. An attacker can exploit this to steal session tokens, redirect users, or perform actions on their behalf.
The safest alternative for inserting plain text content into the DOM is textContent. Unlike innerHTML, it treats whatever string you assign to it as pure text and never parses it as HTML. So even if a user inputs a malicious script tag, it will be rendered as a visible string on the screen rather than executed as code. For example, if a user submits the text <script>alert('hacked')</script> and you insert it using textContent, the browser will literally display that string as text rather than running it.
When you genuinely need to insert HTML dynamically, the right approach is to sanitize the content first using a trusted library like DOMPurify before passing it to innerHTML.
The most dangerous approach is passing raw user input directly into innerHTML with no checks whatsoever:
element.innerHTML = userInput;For any situation involving plain text, always prefer textContent since it completely sidesteps the risk of executing injected markup:
element.textContent = userInput;And when HTML rendering is truly necessary, always sanitize the input through DOMPurify before it ever touches the DOM:
element.innerHTML = DOMPurify.sanitize(userInput);What you need to do is always default to textContent for plain text updates, reach for innerHTML only when HTML rendering is truly necessary, and never trust user input without sanitizing it first.
13. How do you implement client-side form validation UX using HTML constraints + JS enhancements (without re-creating everything in JS)?
The right approach is to let HTML be at the main working point first and use JavaScript only to enhance the experience on top of it, rather than rebuilding validation logic from scratch in JS.
HTML5 provides built-in constraint attributes that handle the most common validation rules out of the box. You can use required to mark a field as mandatory, type="email" or type="url" to enforce format rules, minlength and maxlength to control character limits, and pattern to match a custom regular expression. The browser validates these automatically on form submission without a single line of JavaScript.
JavaScript is used here primarily to enhance the user experience. The browser's default validation messages are generic and unstyled, so JS lets you intercept them and show friendlier, on-brand error messages instead.
A good pattern is to listen for the invalid event on each field and use setCustomValidity() to replace the default message, and then listen for the input event to clear the error as soon as the user starts correcting their input:
input.addEventListener('invalid', () => {
input.setCustomValidity('Please enter a valid email address.');
});
input.addEventListener('input', () => {
input.setCustomValidity('');
});This way, the validation logic still lives in HTML where it belongs, and JavaScript only steps in to make the feedback clearer and more polished for the user.
14. What is Cumulative Layout Shift (CLS), and how can HTML/CSS choices reduce it?
Cumulative Layout Shift, or CLS, is a Core Web Vital metric that measures the visual stability of a webpage. It quantifies how much the page's content unexpectedly moves around during loading. A high CLS score means elements are jumping, shifting, or pushing other content out of place as the page loads, which creates a frustrating and disorienting experience for users. Google uses CLS as part of its page experience ranking signals, so it has both a UX and an SEO impact. A good CLS score is considered to be anything below 0.1.
The most common culprits behind a poor CLS score are images and media loading without reserved dimensions, web fonts swapping in and causing text to reflow, dynamically injected content like banners or ads pushing existing content down, and embeds like iframes appearing without a defined size.
The good news is that most CLS issues can be fixed through deliberate HTML and CSS choices alone, without touching any JavaScript.
1. Always define width and height on images and video elements. When dimensions are set directly in HTML, the browser can reserve the exact space for that media before it finishes downloading, preventing any shift when it finally loads. A complementary CSS approach is to use the aspect-ratio property to maintain proportional space for responsive media.
2. Use the font-display: optional or font-display: swap property carefully in your font face declarations. Fonts that load late and swap in can cause an entire block of text to reflow. Using font-display: optional tells the browser to only use the custom font if it loads fast enough, falling back to the system font otherwise and avoiding a visible swap.
3. Reserve space for dynamic content upfront. If you know an ad banner or a notification bar will appear at the top of the page, define a fixed height container for it in CSS from the start so that when the content loads in, it fills the already-reserved space rather than pushing everything else down:
.ad-banner {
min-height: 90px; /* reserve space before ad loads */
}4. Prefer transform-based animations over layout-affecting properties. Animating top, left, margin, or height directly causes layout recalculations that contribute to the shift. Using transform: translateY() instead moves elements visually without triggering layout, keeping your CLS score clean.
The core principle behind reducing CLS is simply telling the browser as early as possible how much space every element will need, so it never has to reorganize the page after the fact.
15. What is the best way to handle responsive images + performance (conceptually) when you also control CSS and JS behavior?
Responsive image performance is about serving the right image, at the right size, to the right device, without making the browser download more than it needs to. When you control the full stack of HTML, CSS, and JS, you have a powerful set of tools to get this right without relying on any third-party image service.
The foundation starts in HTML with the srcset and sizes attributes on the <img> tag. srcset lets you provide multiple versions of the same image at different resolutions, and sizes tells the browser how wide the image will actually be rendered at different viewport widths. The browser then picks the most appropriate source on its own, factoring in both screen size and pixel density. This alone prevents mobile devices from downloading a massive desktop-sized image.
For art direction, where you want to show a completely different crop or composition of an image on mobile versus desktop, the <picture> element is the right tool.
It lets you define multiple <source> elements with media conditions, so the browser selects the most appropriate one based on the current viewport:
<picture>
<source media="(min-width: 768px)" srcset="hero-desktop.jpg">
<img src="hero-mobile.jpg" alt="Hero image">
</picture>On the CSS side, always avoid setting images to a fixed pixel width. Instead use max-width: 100% so images scale fluidly within their containers without overflowing, and pair it with height: auto to preserve the natural aspect ratio. For background images in CSS, using background-size: cover combined with media queries to swap out the image source at different breakpoints gives you clean control over both appearance and file size.
From the JS side, the biggest performance win is lazy loading. The native loading="lazy" attribute on images is now widely supported and defers the loading of offscreen images until the user scrolls near them, significantly reducing the initial page load weight. For more fine-grained control, the Intersection Observer API lets you implement custom lazy loading logic, for example, only loading an image when it is within a certain distance of the viewport, or triggering a fade-in animation as it loads.
The overall principle is to treat image delivery as a layered decision - HTML handles source selection and lazy loading, CSS handles fluid scaling and art direction fallbacks, and JS steps in only when you need behaviour that goes beyond what the browser provides natively.
HTML MCQ
Which of the following attribute triggers events before the document is printed?
Which of the following attribute triggers events when the document has changed?
Which one is not a semantic html5 element?
Which of the following are not semantic tags?
Which of the following method cancels an ongoing watchPosition call?
What are the correct extensions for saving an HTML file?
Why iframe is used?
Which of the following is correct about custom attributes in HTML5?
Which of the following is not a value of the attribute display?
Using which attribute we can add a tooltip in the HTML element.
Which of the following attribute triggers an event when all the media data of a media element is loaded?
Which of the following attribute specifies if the user can edit the element's content or not?
Which attribute defines the accelerator key to be used for keyboard access to an element.
Comments in HTML is done by:
How to set the playback speed of audio/video?
Which of the following is the correct HTML syntax for adding background color?
Which is the correct attribute to change the size of text?
If you have used inline, internal, and external all the 3 stylings in HTML for a single element then which style will be applied?
Which is the correct HTML syntax for adding a link to the image?
HTML attribute values are case-sensitive?