Table of contents
1.
What is HTML?
2.
Basic HTML Interview Questions
2.1.
1. What do you mean by Tags in HTML?
2.2.
2. Do all HTML tags have an end tag?
2.3.
3. What is formatting in HTML?
2.4.
4. How many types of headings does HTML contain?
2.5.
5. What is the significance of the head and the body tag?
2.6.
6. What is the difference between HTML tags and elements?
2.7.
7. What are empty elements?
2.8.
8. What are the entities in HTML?
2.9.
9. Is <!DOCTYPE html> tag an HTML tag?
2.10.
10. What is the difference between the <link> and the <a> tag?
2.11.
11. What do you mean by alternative text?
2.12.
12. Is older HTML compatible with new browsers?
2.13.
13. Is a hyperlink only applicable to text?
2.14.
14. What is HTML used for?
2.15.
15. What are the 4 basic tags of HTML?
3.
HTML Interview Questions for Freshers
3.1.
16. What do you mean by Image Maps?
3.2.
17. How do you create an email link using a hyperlink in HTML?
3.3.
18. Which HTML tag do we use to display the data in the tabular form?
3.4.
19. What is the use of a span tag? Give an example.
3.5.
20. What is the use of an iframe tag?
3.6.
21. What are some standard lists used when designing a page?
3.7.
22. Explain some of the common lists to design a web page.
3.8.
23. How to create a nested webpage in HTML?
3.9.
24. To what values attribute can be set?
3.10.
25. What is the id attribute in HTML?
3.11.
26. What exactly are applets?
3.12.
27. How to indent list elements?
3.13.
28. How do you create a hyperlink in HTML?
3.14.
29. Is it possible to modify the color of the bullets?
3.15.
30. Does a hyperlink only apply to text?
3.16.
31. What are the 5 basic parts of HTML?
3.17.
32. What are the 3 main elements of HTML?
3.18.
33. What exactly are style sheets?
3.19.
34. How do you make the colorful text on a website?
3.20.
35. Is it possible to customize the colour of the table borders?
4.
HTML Interview Questions for Experienced
4.1.
36. What is the difference between inline, block, and inline-block elements?
4.2.
37. How do you use the <canvas> element in HTML?
4.3.
38. In the middle of a list, how do you change the number type?
4.4.
39. What is the benefit of grouping many checkboxes together?
4.5.
40. How do you make a link that, when clicked, takes you to another web page?
4.6.
41. What is the distinction between the directory, menu, and unordered lists?
4.7.
42. What is the connection between border and rule attributes?
4.8.
43. What distinguishes active links from regular links?
4.9.
44. Do style sheets impose a restriction on the number of additional style definitions that can be inserted between the brackets?
4.10.
45. What is the hierarchy that is followed in stylesheets?
4.11.
46. What happens if the external CSS file is opened in a browser?
4.12.
47. What if the list-style-type property is applied to a non-list element, such as a paragraph?
4.13.
48. When is the use of frames appropriate?
4.14.
49. What exactly is the Application Cache? What are the applications of it?
4.15.
50. What is the distinction between progress and a meter tag?
4.16.
51. What is the difference between the "id" and "class" attributes in HTML?
4.17.
52. What is the purpose of the "alt" attribute in an image tag in HTML?
4.18.
53. How does the browser handle invalid or poorly written HTML? Explain the concept of error tolerance in HTML parsers.
4.19.
54. What are the differences between <section>, <article>, and <div>? When would you use each?
4.20.
55. Explain the concept of the Shadow DOM. How is it implemented in HTML?
4.21.
56. What is the purpose of the data-* attribute in HTML? Provide an example use case.
4.22.
57. What is the difference between the defer and async attributes in the <script> tag? 
4.23.
58. How do ARIA (Accessible Rich Internet Applications) roles work in HTML?
4.24.
59. What is the difference between the display: none; and visibility: hidden; CSS properties?"
4.25.
60. How does the <picture> element work in HTML? Explain its role in responsive image rendering.
5.
Technical HTML Interview Questions.
5.1.
61. What are the different formats in which colors in HTML can be declared?
5.2.
62. What is the difference between <div> and <span>?
5.3.
63. What are semantic HTML elements? Provide examples.
5.4.
64. How do you create a table in HTML?
5.5.
65. How do you include a JavaScript file in HTML?
5.6.
66. What is the difference between placing the <script> tag in the <head> and the <body>?
5.7.
67. How do you create a form in HTML?
5.8.
68. How do you create a dropdown list in HTML?
5.9.
69. How do you define metadata in an HTML document?
5.10.
70. What is the difference between the id and class attributes?
5.11.
71. What are the global attributes in HTML? Provide examples.
5.12.
72. How do you create a responsive design using HTML?
5.13.
73. Explain the purpose of the doctype declaration in HTML.
5.14.
74. What is the difference between HTML5 and earlier versions of HTML?
5.15.
75. What is the use of the target attribute in the <link> tag?
6.
HTML5 Interview Questions and Answers
6.1.
76. What is HTML5?
6.2.
77. What is meant by HTML Entities?
6.3.
78. Do HTML tags and elements refer to the same entities?
6.4.
79. What is meant by ‘class’ attribute in HTML?
6.5.
80. What is multipart form data in HTML?
6.6.
81. What are tags in HTML5?
6.7.
82. List some new tags in HTML5.
6.8.
83. What are void tags in HTML5?
6.9.
84. What are the attributes in HTML5?
6.10.
85. How many tags were removed in HTML5?
6.11.
86. How does HTML5 handle offline web applications? Discuss the role of the manifest attribute.
6.12.
87. What is a polyfill, and how is it relevant to HTML5 features? Provide an example of a scenario where a polyfill is necessary
6.13.
88. Explain the <canvas> element in HTML5. How does it differ from the <svg> element in terms of rendering and use cases?
6.14.
89. Explain the concept of the contenteditable attribute in HTML5. What are the limitations and best practices for using it? 
6.15.
90. What is the purpose of the sandbox attribute in the <iframe> element? How does it enhance security?
7.
Conclusion
Last Updated: Dec 31, 2024
Easy

HTML Interview Questions and Answers

Author Rinki Deka
1 upvote
html interview questions

HTML is the foundation of any web development interview. As a result, it is critical to have a solid understanding of this subject. But don't be concerned about any of it. Ninjas are here to help, and today we'll talk about top HTML interview questions.

What is HTML?

HTML (Hypertext Markup Language) is a programming language used to create documents and web pages on a web server. HTML is required for the development of any website, web application, or other application. As a result, experts with HTML development skills are in high demand. Now, let's talk about HTML interview questions.

A list of the top most asked HTML interview questions and answers are given below.

Basic HTML Interview Questions

1. What do you mean by Tags in HTML?

Tags in HTML are the building blocks used to define and structure content on a webpage. They are enclosed in angle brackets (< >) and usually come in pairs: an opening tag (e.g., <p>) and a closing tag (e.g., </p>). Tags tell the browser how to interpret and display the content within them.

2. Do all HTML tags have an end tag?

No, some HTML tags don't need a closing tag.

 For example: <image> tag, <input> tag, <hr>tag, <meta>tag, <br> tag, etc.

3. What is formatting in HTML?

Formatting in HTML refers to using tags to style and display text in a specific way, such as bold, italic, underlined, or highlighted. It enhances the appearance of content on a webpage.

Example Tags:

  • <b>: Bold text
  • <i>: Italic text
  • <u>: Underlined text
  • <mark>: Highlighted text

4. How many types of headings does HTML contain?

The HTML contains six different types of headings which are defined from <h1> to <h6> tags. Each type of heading tag displays a different text size. <h1> is the largest and <h6> is the smallest heading tag. 

For example:

<h1>This is Heading h1</h1>
<h2>This is Heading h2</h2>
<h3>This is Heading h3</h3>
<h4>This is Heading h4</h4>
<h5>This is Heading h5</h5>
<h6>This is Heading h6</h6>

5. What is the significance of the head and the body tag?

The head tag is used to define the information regarding the document, whereas the body tag is used to describe the actual content or the body of the document. 

6. What is the difference between HTML tags and elements?

HTML elements correspond to the browser to render text. When we enclose the elements by brackets <>, they form an HTML tag. Most of the time, tags are in a pair and hold content.

7. What are empty elements?

HTML elements with no content are called empty elements. For example: <br>, <hr> etc.

8. What are the entities in HTML?

We use the HTML entities to replace reserved characters in HTML. You can also replace characters not present on your keyboard with entities. We replace these characters because some characters are reserved in HTML.

9. Is <!DOCTYPE html> tag an HTML tag?

No, the <!DOCTYPE> declaration is not an HTML tag. We use <!DOCTYPE> to instruct the web browser about the HTML page

10. What is the difference between the <link> and the <a> tag?

The <link> tag is used to define a link between the given URL and the HTML document, whereas the <a> tag is used to add a hyperlink to the webpage.

11. What do you mean by alternative text?

When using picture maps, determining which hotspots belong to which links can quickly become complex and challenging. You can use alternative text to add descriptive information to each hotspot connection.

12. Is older HTML compatible with new browsers?

Yes, older HTML files are HTML standard compliant. Most older files are compatible with newer browsers, though some functions may not be available.

13. Is a hyperlink only applicable to text?

No, hyperlinks can be used in both text and graphics. That is, you can turn an image into a link that will take viewers to another page when clicked. a href=" ">.../a> tag combinations should be used to surround the image.

14. What is HTML used for?

HTML also known as Hypertext Markup Language is basically used for creating web pages and structuring them. It helps one describe the structure of the web page with only text-based content, including paragraphs, links, lists, images, etc. It is the first one taken while creating web pages or web applications.

15. What are the 4 basic tags of HTML?

<html>: It defines the beginning and the end of an HTML document.

<head>: It contains the metadata (it is used to specify page description, keywords or author name) of a webpage.

<title>: It defines the title of the HTML document. The title appears in the browser's title bar.

<body>: It contains the main body or content that is to be added to the HTML page such as text, images, or any other multimedia elements.

HTML Interview Questions for Freshers

16. What do you mean by Image Maps?

You can use an image map to link to multiple web pages by using a single image. You can define shapes in photographs that will be used in image mapping.

17. How do you create an email link using a hyperlink in HTML?

To create an email link in HTML, use the <a> tag with the mailto: protocol in the href attribute.

Example:

<a href="mailto:example@example.com">Send an Email</a>

When clicked, this opens the user's default email client with the recipient's email pre-filled.

18. Which HTML tag do we use to display the data in the tabular form?

We use the HTML table tag to show data in tabular form (row * column). It also handles the layout of the page, e.g., header section, navigation bar, body content, footer section. Below is the list of tags used while depicting the data in the tabular form:

  • <table> - It represents a table.
  • <tr> - It represents a row in a table.
  • <th> - It represents a header cell in a table.
  • <td> - It represents a cell in a table.
  • <caption> - It represents the table caption.
  • <colgroup> - It defines a group of one or more columns in a table for formatting.
  • <col> - We use it with <colgroup> element to specify column properties for each column.
  • <tbody> - We use it to group the body content in a table.
  • <thead> - We use it to group the header content in a table.
  • <tfooter> - We use it to group the footer content in a table.

19. What is the use of a span tag? Give an example.

We use the span tag for the following things:

  • For adding color to text
  • For adding background on text
  • Highlight any color text

Example:

<p>  
<span style="color:#ffffff;">  
On this page we use span.  
</span>  
</p>

20. What is the use of an iframe tag?

We use an iframe tag in HTML to display a web page within a web page.

Syntax:

<iframe src=" ... "></iframe> 

Example:

<iframe src="iframe.html" width="400px" height="400px"</iframe>

21. What are some standard lists used when designing a page?

We use many standard lists to design a page. We can choose any or a combination of the following types of list:

  • Ordered list Ordered list displays elements in a numbered format. It is represented by <ol> tag.
  • Unordered list - It displays elements in bullet point format. It is represented by <ul> tag.
  • Definition list - It displays elements like in a dictionary. we use <dl>, <dt> and <dd> tags to define description list.

22. Explain some of the common lists to design a web page.

The common lists to design a web page include:

  • Ordered list
  • Directory list
  • Menu list
  • Unordered list
  • Definition list

23. How to create a nested webpage in HTML?

We use the HTML iframe tag to display a nested webpage. In other words, it describes a webpage within a webpage. The HTML <iframe> tag portrays an inline frame.

To create a nested webpage in HTML, you simply create multiple HTML files and link them together using anchor (<a>) tags, forming a hierarchical structure. Each HTML file can represent a separate page, and you can link from one to another to create a nested navigation structure.

Steps:

  1. Create multiple HTML files: For example, you can have index.html (main page) and page2.html (nested page).
  2. Link pages using <a> tag: Inside index.html, you link to page2.html (or other pages) to navigate between them.

Example:

index.html (Main page)

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Main Page</title>
</head>
<body>

  <h1>Welcome to the Main Page</h1>
  <p>This is the main webpage.</p>
  
  <p>Click here to go to the <a href="page2.html">Nested Page 2</a></p>

</body>
</html>

 

page2.html (Nested page)

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Page 2</title>
</head>
<body>

  <h1>This is the Nested Page 2</h1>
  <p>You have navigated to the second page.</p>
  
  <p>Click here to go back to the <a href="index.html">Main Page</a></p>

</body>
</html>

 

How it works:

  • The main page (index.html) has a link (<a href="page2.html">) that takes you to page2.html.
  • On page2.html, there is a link back to index.html.
  • The two pages are "nested" in the sense that one links to the other, forming a simple hierarchical navigation.

24. To what values attribute can be set?

Only predefined values can be assigned to some attribute values. Other characteristics can accept any integer value representing the number of pixels in size.

25. What is the id attribute in HTML?

HTML id attribute performs the same function as the class attribute. It is used to add an id to an element. Like the class attribute, the id attribute is also generally associated with the stylesheets.

26. What exactly are applets?

Applets are small programs that can be embedded within web pages to accomplish specific tasks such as computations, animations, and data processing. The Java programming language is used to create applets. 

27. How to indent list elements?

By utilizing indents, you can keep the list of components straight. If you indent each sub-nested list deeper than the parent list that includes it, you can see the various lists and the components that they contain at a glance. 

28. How do you create a hyperlink in HTML?

We will use the anchor tag <a> and specify the URL of the webpage one wants to link to in the href attribute to create a hyperlink in HTML. For example: 

<a href="https://example.com">Link text</a> 


would create a hyperlink with the text "Link text" that, when clicked, would take the user to the webpage at the URL "https://example.com".

29. Is it possible to modify the color of the bullets?

The color of the bullet is always the same as the color of the first character in the list item. If you surround the <li> and the first character with a set of <font> tags with the color property set, the bullet color and, first character will be different colors than the text.

30. Does a hyperlink only apply to text?

No, you can use hyperlinks on both text and images. The HTML anchor tag <a> defines a hyperlink that connects one page. The "href" attribute is the most crucial attribute of the HTML anchor tag.

Syntax

<a href = " ... "> Link Text </a>

31. What are the 5 basic parts of HTML?

Document Type Declaration (<!DOCTYPE html>): It helps us define the version of HTML used

HTML tag (<html>): it defines the beginning and is the root tag that includes all the subsequent tags.

Head tag (<head>): It defines metadata which includes title, styles, author name, etc.

Body tag (<body>): It contains the main body or content that is to be added to the HTML page such as text, images, or any other multimedia elements.

Closing HTML tag (</html>): It is used to close the HTML document.

32. What are the 3 main elements of HTML?

The three main elements of HTML are:

Tags: it is used to define the purpose of a particular web page and to markup the HTML elements present in the body of HTML.

AttributesAttributes in HTML provides extra information on how the HTML elements should appear or behave.
Text Content: it helps one to display the content on the web page. It can be formatted by using HTML tags and attributes

33. What exactly are style sheets?

Style sheets allow you to create style templates that are uniform, portable, and well-defined. These templates can be linked to a variety of online sites, making it simple to maintain and change the look and feel of the entire site's web pages. 

34. How do you make the colorful text on a website?

Use the tag <font color=”color”>…</font>. to create text with different colours. /font> tags for each character to which color should be applied. Html Font color tag combinations can be used as many times as needed to surround a single character or an entire word.

35. Is it possible to customize the colour of the table borders?

Style sheets can be used to set a border colour, but the border colours for a table that is not styled using style sheets will be the same as the text color. 

HTML Interview Questions for Experienced

36. What is the difference between inline, block, and inline-block elements?

Comparison of inlineblock, and inline-block elements in HTML:

PropertyInlineBlockInline-Block
Display BehaviorElements are displayed on the same line as other inline elements.Elements take up the full width of their container, breaking onto a new line.Elements are displayed on the same line like inline elements but can have width and height like block elements.
Width and HeightCannot set width or height (height is based on content).Can set width and height.Can set width and height.
Example<span>, <a>, <strong><div>, <p>, <header>, <footer><img>, <button>, <input> (with display:inline-block)
Line BreakDoes not cause a line break; stays within the flow of content.Always starts on a new line, pushing subsequent content below.Does not cause a line break, but respects width/height properties like block elements.
UsageUsed for elements that are part of text or content flow (e.g., links, small pieces of text).Used for larger structural elements like sections, divs, and headers.Used for elements that need to behave like inline elements but need block-like properties (e.g., buttons, form inputs).
AlignmentCannot have margin/padding on the left and right to affect layout; alignments are often controlled with text-align.Can have margins and paddings on all sides.Can have margins and paddings on all sides, and elements align inline like text.

Example Usage:

<!-- Inline element (no line break) -->
<span>This is an inline element</span> with more text.
<!-- Block element (new line starts) -->
<div>This is a block element</div>
<!-- Inline-block element (same line, but can have width/height) -->
<button style="display:inline-block; width: 100px; height: 50px;">Click Me</button>

37. How do you use the <canvas> element in HTML?

The <canvas> element in HTML is used to draw graphics via JavaScript. It provides a space on the page where you can render 2D shapes, images, or even animations.

Basic Structure:

<canvas id="myCanvas" width="500" height="500"></canvas>
  • id: Identifies the canvas element, so you can reference it in JavaScript.
  • width and height: Define the size of the canvas. If not specified, the default size is 300px by 150px.

Drawing on the Canvas:

To draw graphics on the canvas, you need to use JavaScript to access the canvas context. The context provides methods for drawing shapes, lines, text, and images.

Example of Drawing on the Canvas:

<canvas id="myCanvas" width="500" height="500"></canvas>


<script>
  // Get the canvas element by its id
  var canvas = document.getElementById("myCanvas");


  // Get the 2D context for drawing
  var ctx = canvas.getContext("2d");


  // Draw a red rectangle
  ctx.fillStyle = "red";  // Set the color to red
  ctx.fillRect(50, 50, 200, 100);  // Draw rectangle at (50, 50) with width 200px and height 100px


  // Draw a blue circle
  ctx.beginPath();
  ctx.arc(300, 150, 50, 0, 2 * Math.PI);  // Circle at (300, 150) with radius 50px
  ctx.fillStyle = "blue";  // Set the color to blue
  ctx.fill();  // Fill the circle with blue
</script>


Output 

canvas element in HTML

38. In the middle of a list, how do you change the number type?

To change the number type in the middle of an ordered list (<ol>), you can use the type attribute on the <li> elements where you want the numbering to change.

Example:

<ol>
  <li>Item 1</li>
  <li>Item 2</li>
  <li type="A">Item 3 (Alphabetical)</li> <!-- Changes numbering to letters -->
  <li>Item 4</li>
  <li type="i">Item 5 (Roman numerals)</li> <!-- Changes to Roman numerals -->
</ol>

 

Output 

How do you change the number type

In this example:

  • The third item uses letters (A, B, etc.).
  • The fifth item uses Roman numerals (i, ii, etc.).

Note: The type attribute can be set to 1 (default), A (uppercase letters), a (lowercase letters), I (uppercase Roman numerals), or i (lowercase Roman numerals).

39. What is the benefit of grouping many checkboxes together?

Benefits of grouping many checkboxes together:

  • Improved Organization: Helps in organizing related options, making the form more structured and easier to understand.
  • Better User Experience: Users can quickly scan and select multiple related options without confusion.
  • Logical Grouping: Allows users to interpret the checkboxes as belonging to the same category or set of choices.
  • Efficient Form Submission: Grouped checkboxes can be submitted as a single form element with an array of values, simplifying the handling of data.
  • Easier Styling and Accessibility: You can style or manage the group of checkboxes collectively, improving accessibility for screen readers.

40. How do you make a link that, when clicked, takes you to another web page?

To create a link that takes you to another webpage, use the <a> (anchor) tag with the href attribute specifying the destination URL.

Example:

<a href="https://www.example.com">Go to Example</a>

41. What is the distinction between the directory, menu, and unordered lists?

The <dir><menu>, and <ul> (unordered list) elements are all used for listing items in HTML, but they have distinct purposes and behaviors.

Key Differences:

ElementPurposeTypical UseDeprecated
<dir>Represents a directory of items (historically used for navigation).Used to list items like file directories (now rarely used).Yes (deprecated in HTML 4.01 and not part of HTML5).
<menu>Represents a list of commands or options, often for user actions (like a context menu).Used for commands or actions, such as in a right-click context menu.No (still valid in HTML5).
<ul>Represents an unordered list of items, usually for general content or navigation.Commonly used to create unordered lists like bullet points.No (standard HTML element).

42. What is the connection between border and rule attributes?

If the border property is set to a nonzero value, default cell boundaries with a thickness of one pixel are automatically placed between cells. Similarly, if the rules property is added to the table> tag but the border attribute is not provided, a default 1-pixel border emerges.

43. What distinguishes active links from regular links?

Blue is the default color for normal and active links. When the mouse pointer is over a link, some browsers recognize it as active; others recognize it as active when the link has the focus. Those that do not have the mouse cursor over the link are regarded as normal. 

44. Do style sheets impose a restriction on the number of additional style definitions that can be inserted between the brackets?

The number of style definitions that can be inserted within the brackets for a particular selection is not limited by style sheets. However, each new style specification must be separated from the others by a semicolon symbol. 

45. What is the hierarchy that is followed in stylesheets?

If a single selector contains three alternative style declarations, the one closest to the actual tag takes precedence. Inline style takes precedence over embedded style sheets, which in turn take precedence over external style sheets. 

46. What happens if the external CSS file is opened in a browser?

It fails since the extension is different. The only way to use an external CSS file is to use the <link/> tag within another HTML document. 

47. What if the list-style-type property is applied to a non-list element, such as a paragraph?

When the list-style-type property is applied to a non-list element, it has no effect on the paragraph. 

48. When is the use of frames appropriate?

Frames make it much easier to navigate through a website. If the primary site links are in a frame that displays at the top or along the edge of the browser, the information for those links can be displayed in the browser window's remaining space. 

49. What exactly is the Application Cache? What are the applications of it?

Application Cache in HTML5 allows a web application to store resources (like HTML, CSS, JavaScript, and images) locally on the user's device. This enables the application to function offline or with limited connectivity.

Applications:

  1. Offline Access: Ensures web apps work even when there is no internet connection.
  2. Faster Loading: Resources load quickly from the local cache, reducing server requests.
  3. Reduced Server Load: Limits the need for frequent requests to the server, improving efficiency.
  4. Improved User Experience: Provides seamless access to applications regardless of network availability.

Note: Application Cache is deprecated; modern web development uses Service Workers for offline capabilities.

50. What is the distinction between progress and a meter tag?

The <progress> and <meter> tags in HTML5 are both used to represent data in a visual format, but they serve different purposes and are used in different contexts. Here’s a breakdown of their distinctions:

1. <progress> Tag

  • Purpose: Represents the progress of a task or operation that is ongoing.
  • Use Case: Typically used to show the progress of a task such as downloading a file, completing a form, or performing a computation.
  • Value Range: The value of a <progress> element ranges from 0 (0% complete) to 1 (100% complete). It usually represents a specific task or operation’s progress over time.

2. <meter> Tag

  • Purpose: Represents a scalar measurement within a known range, such as a gauge or a score.
  • Use Case: Typically used to display a value within a given range, such as temperature, battery level, or score on a test. It’s useful for indicating a value relative to a maximum or minimum range but does not imply ongoing progress.
  • Value Range: The value of a <meter> element typically falls within a defined range (e.g., from 0 to 100) but does not represent a process. It’s more about showing a static value relative to its range.

Key Differences:

Feature<progress><meter>
PurposeRepresents progress of a task or operation.Represents a scalar measurement or value within a range.
Value ContextUsed for ongoing tasks (e.g., file download).Used for static values (e.g., temperature, score).
Typical Use CaseFile downloads, task completion, loading states.Battery level, test scores, sensor readings.
RangeTypically ranges from 0 to 1 (0% to 100%).Typically has a defined min and max range (e.g., 0-100).
InteractiveUsually doesn't accept user input.Displays data but may be used in some interactive contexts.

51. What is the difference between the "id" and "class" attributes in HTML?

The "id" attribute is used to uniquely identify a single element on a page, while the "class" attribute is used to group multiple elements together and apply styling or any functionality to them collectively.

52. What is the purpose of the "alt" attribute in an image tag in HTML?

The purpose of the “alt” attribute in HTML is that it is used for an alternative text description when the image is not displayed due to various reasons such as slow internet connectivity, etc. Also, it helps visually impaired users to understand what the image wants to tell with the help of screen readers.

53. How does the browser handle invalid or poorly written HTML? Explain the concept of error tolerance in HTML parsers.

HTML browsers are designed with error tolerance to handle invalid or poorly written HTML. When an HTML document contains errors or is not well-formed, the browser doesn't typically stop rendering the page. Instead, it tries to "fix" the errors by making assumptions to display the content as correctly as possible. This includes:

  • Missing closing tags: The browser will infer where tags should close.
  • Mismatched or incorrect attributes: Browsers may ignore or adjust them.
  • Improper nesting of elements: Browsers will adjust the structure to display the page.

This error tolerance helps ensure that users still see content even if there are issues in the code, but it can sometimes lead to unexpected behavior or layout problems.

54. What are the differences between <section>, <article>, and <div>? When would you use each?

The <section><article>, and <div> elements are all used for grouping content in HTML, but they serve different purposes and have distinct semantic meanings.

Key Differences:

ElementPurposeUse CaseSemantic Meaning
<section>Represents a thematic grouping of content, typically with a heading.Used for grouping related content within a page, like a blog post, product section, or a chapter in a book.Indicates a distinct section of content with a specific theme.
<article>Represents a self-contained, independent piece of content that can stand alone.Used for content that can be distributed or syndicated, like a news article, blog post, or forum post.Denotes a complete unit of content that makes sense on its own.
<div>A generic container with no semantic meaning, often used for layout or styling.Used for grouping content for styling or layout purposes, or when no semantic element is appropriate.No specific meaning; purely for grouping and styling.

When to Use Each:

1) <section>: Use when you want to group content by topic or theme. It typically includes a heading (<h1> to <h6>).

  • Example: Grouping related sections of an article, like an introduction, main content, and conclusion.
<section>
  <h2>Introduction</h2>
  <p>Welcome to the article...</p>
</section>

2) <article>: Use when the content is a standalone unit that could be redistributed or makes sense on its own (e.g., a blog post or news article).

  • Example: A single blog post or a product description.
<article>
  <h2>Latest News</h2>
  <p>Breaking news goes here...</p>
</article>

3) <div>: Use when you need a generic container for styling or layout purposes, without any specific semantic meaning.

  • Example: Wrapping content for CSS styling or JavaScript manipulation.
<div class="container">
  <p>This content is styled with a container class.</p>
</div>

55. Explain the concept of the Shadow DOM. How is it implemented in HTML?

The Shadow DOM is a web standard that allows for encapsulating a part of a webpage's DOM (Document Object Model) to create isolated, self-contained elements. It enables developers to build components with their own structure, style, and behavior, which are separate from the main document. This helps avoid style or script conflicts and provides better modularity.

Key Features:

  • Encapsulation: Styles and scripts in the shadow tree don’t affect the main DOM.
  • Scoped Styles: Styles inside a shadow DOM only apply to its elements, not the rest of the page.

How it's implemented:

  1. Create a shadow root on an element using JavaScript.
  2. Add content (HTML, styles, and scripts) to the shadow DOM.

Example:

<div id="host"></div>

<script>
  const host = document.getElementById('host');
  const shadowRoot = host.attachShadow({mode: 'open'});  // Create shadow DOM
  shadowRoot.innerHTML = `
    <style>p { color: red; }</style>
    <p>This is inside the shadow DOM!</p>
  `;
</script>

56. What is the purpose of the data-* attribute in HTML? Provide an example use case.

The data-* attribute in HTML is used to store custom data on HTML elements. It allows developers to embed extra information in elements that can be accessed and manipulated via JavaScript, without affecting the rendering or behavior of the page. The attribute is designed to store non-visible data that is associated with an element but doesn't have a specific meaning in HTML itself.

Purpose:

  • Custom data storage: Store additional information that can be accessed programmatically.
  • Separation of data from structure: It allows data to be kept with the relevant element, without affecting the element's appearance or functionality.

Syntax:

<data-attribute="value">


Example Use Case:

Suppose you're building a product catalog, and you want to store the product's price and ID in each item, without displaying them in the HTML.

<div class="product" data-id="123" data-price="19.99">
  <h2>Product Name</h2>
  <p>Description of the product.</p>
  <button class="buy-btn">Buy Now</button>
</div>
<script>
  const product = document.querySelector('.product');
  const productId = product.getAttribute('data-id');  // Access the data-id attribute
  const productPrice = product.getAttribute('data-price');  // Access the data-price attribute
  console.log(`Product ID: ${productId}, Price: $${productPrice}`);
</script>

57. What is the difference between the defer and async attributes in the <script> tag? 

The defer and async attributes in the <script> tag are both used to control the loading and execution behavior of external JavaScript files, but they work differently.

Key Differences:

Attributedeferasync
Execution TimingScripts are executed in order after the document has been fully parsed.Scripts are executed as soon as they are downloaded, without waiting for the document to finish parsing.
Script LoadingScripts are downloaded in parallel but executed after the HTML parsing completes.Scripts are downloaded in parallel and executed as soon as they are ready, possibly interrupting HTML parsing.
Order of ExecutionScripts are executed in the order they appear in the document.Scripts can execute out of order, depending on which one finishes downloading first.
Use CaseIdeal for scripts that depend on the DOM being fully loaded but need to be non-blocking (e.g., analytics, UI enhancements).Best for independent scripts that do not depend on DOM or other scripts, like tracking or ad scripts.

58. How do ARIA (Accessible Rich Internet Applications) roles work in HTML?

ARIA (Accessible Rich Internet Applications) roles and attributes are used to enhance web accessibility, especially for users with disabilities who rely on assistive technologies like screen readers. ARIA attributes provide additional semantic information to elements, helping assistive technologies interpret and interact with complex UI components such as dynamic content, widgets, and controls.

How ARIA Roles Work:

  • ARIA roles provide meaning to an element that may not have native semantic meaning in HTML (e.g., a custom button).
  • ARIA attributes give additional context, such as states or properties, to improve user interaction and accessibility.

Common ARIA Roles:

  1. role="button": Specifies that an element behaves like a button.
  2. role="navigation": Denotes a navigation section.
  3. role="alert": Specifies an important, dynamic message.
  4. role="dialog": Indicates a dialog box or modal window.
  5. role="main": Denotes the primary content of the document.

59. What is the difference between the display: none; and visibility: hidden; CSS properties?"

The difference between display: none; and visibility: hidden; in CSS is:

  • display: none;: Hides the element completely from the page. The element is removed from the layout, and it no longer takes up space in the document flow.
  • visibility: hidden;: Hides the element but keeps it in the page layout. The element is still present but invisible, and it still takes up space in the document flow.

Key Differences:

Propertydisplay: none;visibility: hidden;
Space OccupiedDoes not occupy space (removed from flow).Occupies space (still part of flow).
Effect on LayoutAffects layout (elements shift).Does not affect layout (space remains).
InteractivityThe element is not interactive.The element is still not interactive.

60. How does the <picture> element work in HTML? Explain its role in responsive image rendering.

The <picture> element in HTML is used to provide multiple image sources for different display conditions, allowing browsers to choose the most appropriate image based on factors like screen size, resolution, and other features. This helps in responsive image rendering, ensuring optimal image display on various devices.

Key Features:

  • The <picture> element contains one or more <source> elements, each specifying different image files and conditions (e.g., for specific screen widths or pixel densities).
  • The <img> element within <picture> serves as a fallback if no conditions match.

Example:

<picture>
  <source srcset="https://files.codingninjas.com/new-cn-logos-1-1733819445.svg" media="(min-width: 1024px)">
  <source srcset="https://files.codingninjas.com/new-cn-logos-1-1733819445.svg" media="(min-width: 600px)">
  <img src="https://files.codingninjas.com/new-cn-logos-1-1733819445.svg" alt="Responsive Image">
</picture>


Output

 

How it Works:

  • The browser will first check the conditions in the <source> elements (e.g., screen width).
  • If a condition matches, the corresponding image is loaded.
  • If no conditions match, the <img> element’s src is used as the fallback.

Technical HTML Interview Questions.

61. What are the different formats in which colors in HTML can be declared?

Different formats for colour in HTML

Colors in HTML can be declared in several formats:

  1. Hexadecimal: e.g., #FF5733, representing red, green, and blue (RGB) values in hexadecimal.
  2. RGB: e.g., rgb(255, 87, 51), specifying the intensity of red, green, and blue on a scale of 0–255.
  3. RGBA: e.g., rgba(255, 87, 51, 0.5), adding an alpha channel for transparency (0–1).
  4. HSL: e.g., hsl(16, 100%, 60%), using hue, saturation, and lightness.
  5. HSLA: e.g., hsla(16, 100%, 60%, 0.5), adding an alpha channel for transparency.
  6. Named Colors: e.g., red, blue, coral, etc., using predefined color names.

These formats provide flexibility for styling elements.

62. What is the difference between <div> and <span>?

Here’s a Table highlighting the differences between <div> and <span>:

Feature<div><span>
PurposeBlock-level containerInline-level container
Display BehaviorStarts on a new line (block)Stays on the same line (inline)
Use CaseGrouping larger structuresStyling or grouping inline text
StylingOften used with CSS for layoutUsed for inline styling
SemanticsNo semantic meaningNo semantic meaning

Both are non-semantic elements but are widely used for structuring and styling HTML content.

63. What are semantic HTML elements? Provide examples.

Semantic HTML Elements

Semantic HTML elements are those that clearly describe their meaning and purpose within the context of a web page. These elements provide better structure and improve accessibility, readability, and SEO.

Examples:

  1. Structural Elements:
    • <header>: Represents the introductory content or navigation links.
    • <nav>: Represents a section of navigation links.
    • <main>: Represents the main content of the document.
    • <footer>: Represents the footer content, typically including authorship, copyright, or contact information.
    • <section>: Defines a thematic grouping of content.
  2. Text Content Elements:
    • <article>: Represents a self-contained piece of content, like a blog post.
    • <aside>: Represents content related to the main content, such as a sidebar or pull quotes.
    • <summary>: Provides a summary for a <details> element.
    • <figure>: Represents a figure, such as an image with a caption.
  3. Other Semantic Elements:
    • <form>: Represents a container for input elements and user interaction.
    • <table>: Represents tabular data.
    • <mark>: Highlights text that has relevance or importance.
    • <time>: Represents a date or time.

64. How do you create a table in HTML?

To create a table in HTML, you use the <table> element along with several child elements for structure and content. Here's a breakdown of the key elements:

  1. Basic Elements:
    • <table>: The container for the table.
    • <tr>: Represents a table row.
    • <td>: Represents a table cell (data).
    • <th>: Represents a table header cell (usually bold and centered).
  2. Optional Elements:
    • <caption>: Provides a title for the table.
    • <thead>: Groups header rows.
    • <tbody>: Groups body rows.
    • <tfoot>: Groups footer rows.

Example:

<table border="1">
  <caption>Sample Table</caption>
  <thead>
    <tr>
      <th>Header 1</th>
      <th>Header 2</th>
      <th>Header 3</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Row 1, Cell 1</td>
      <td>Row 1, Cell 2</td>
      <td>Row 1, Cell 3</td>
    </tr>
    <tr>
      <td>Row 2, Cell 1</td>
      <td>Row 2, Cell 2</td>
      <td>Row 2, Cell 3</td>
    </tr>
  </tbody>
</table>


Output:

create a table in HTML

65. How do you include a JavaScript file in HTML?

To include a JavaScript file in an HTML document, use the <script> element with the src attribute to specify the file's path. The script tag can be placed in either the <head> or <body> section, depending on when you want the script to load.

Example:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Include JavaScript</title>
  <!-- Include JavaScript in the head -->
  <script src="script.js" defer></script>
</head>
<body>
  <h1>Hello, World!</h1>
  <!-- Include JavaScript at the end of the body -->
  <script src="another-script.js"></script>
</body>
</html>

66. What is the difference between placing the <script> tag in the <head> and the <body>?

The placement of the <script> tag in the <head> or <body> can affect the loading and execution behavior of the script and the overall performance of the webpage.

AspectIn <head>In <body>
Loading OrderThe script is loaded before the page content.The script is loaded after the page content.
Page RenderingCan delay rendering as the browser stops to load and execute the script.Allows the page content to load before executing the script.
Use CaseSuitable for small scripts or scripts that configure the page (e.g., analytics).Ideal for scripts that interact with page elements.
Performance ImpactMay slow down page loading if not deferred or asynchronous.Improves initial page rendering and perceived speed.
Best PracticesUse the defer attribute to prevent blocking the page load.Place at the end of <body> for scripts without defer.

67. How do you create a form in HTML?

To create a form in HTML, use the <form> element along with various input and interactive elements. The <form> tag defines the container for the form and specifies how data is submitted.

Basic Structure:

<form action="submit_url" method="post">
  <!-- Form fields go here -->
</form>


Common Attributes:

  1. action: Specifies the URL where the form data will be sent.
  2. method: Specifies the HTTP method (GET or POST) to use when submitting the form.
  3. name: Identifies the form (optional).
  4. enctype: Specifies the encoding type for form data (e.g., multipart/form-data for file uploads).

Example Form:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Sample Form</title>
</head>
<body>
  <form action="/submit" method="post">
    <!-- Text Input -->
    <label for="name">Name:</label>
    <input type="text" id="name" name="name" required>
    
    <!-- Email Input -->
    <label for="email">Email:</label>
    <input type="email" id="email" name="email" required>
    
    <!-- Password Input -->
    <label for="password">Password:</label>
    <input type="password" id="password" name="password" required>
    
    <!-- Radio Buttons -->
    <p>Gender:</p>
    <label>
      <input type="radio" name="gender" value="male"> Male
    </label>
    <label>
      <input type="radio" name="gender" value="female"> Female
    </label>
    
    <!-- Checkbox -->
    <label>
      <input type="checkbox" name="subscribe"> Subscribe to newsletter
    </label>
    
    <!-- Dropdown -->
    <label for="country">Country:</label>
    <select id="country" name="country">
      <option value="us">United States</option>
      <option value="uk">United Kingdom</option>
      <option value="ca">Canada</option>
    </select>
    
    <!-- Submit Button -->
    <button type="submit">Submit</button>
  </form>
</body>
</html>


Output

create a form in HTML

68. How do you create a dropdown list in HTML?

To create a dropdown list in HTML, use the <select> element along with <option> elements to define the list items.

Basic Syntax:

<select name="dropdown_name">
  <option value="value1">Option 1</option>
  <option value="value2">Option 2</option>
  <option value="value3">Option 3</option>
</select>


Attributes:

  1. name: Specifies the name of the dropdown for form submission.
  2. id: Provides a unique identifier for styling or scripting.
  3. value: Specifies the value submitted when the option is selected.
  4. selected: Sets an option as the default selected item.

Example:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Dropdown Example</title>
</head>
<body>
  <form action="/submit" method="post">
    <label for="country">Choose your country:</label>
    <select id="country" name="country" required>
      <option value="us">United States</option>
      <option value="uk">United Kingdom</option>
      <option value="ca">Canada</option>
      <option value="au">Australia</option>
    </select>
    <button type="submit">Submit</button>
  </form>
</body>
</html>


Output

create a dropdown list in HTML

69. How do you define metadata in an HTML document?

Metadata in an HTML document is defined using the <meta> tag inside the <head> section. It provides information about the page, such as character set, author, description, keywords, and viewport settings for browsers and search engines.

Example:

<head>
  <meta charset="UTF-8">
  <meta name="description" content="A sample HTML document">
  <meta name="keywords" content="HTML, metadata, example">
  <meta name="author" content="Your Name">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>

70. What is the difference between the id and class attributes?

Difference Between ID and Class Attributes

The id and class attributes in HTML are both used to identify elements for styling and scripting, but they have different purposes and behaviors:

Attributeidclass
UniquenessMust be unique within a page (only one element can have a specific id).Can be used on multiple elements, allowing for shared styling or behavior.
PurposeIdentifies a single element for styling or manipulation (e.g., JavaScript or CSS).Groups multiple elements for shared styling or behavior.
CSS SelectorReferenced using # (e.g., #elementId).Referenced using . (e.g., .elementClass).
UsageIdeal for uniquely identifying elements (e.g., for JavaScript manipulation, anchors, or linking).Ideal for applying the same styles or behavior to a group of elements.

71. What are the global attributes in HTML? Provide examples.

Global attributes in HTML are attributes that can be applied to almost any HTML element. These attributes provide additional functionality, such as accessibility, styling, or event handling.

Common Global Attributes:

  1. id: Specifies a unique identifier for an element.
    • Example: <div id="container">Content</div>
  2. class: Assigns one or more class names to an element, often for styling or JavaScript.
    • Example: <p class="text-center">Hello World</p>
  3. style: Specifies inline CSS styles for an element.
    • Example: <h1 style="color: blue;">Hello</h1>
  4. title: Provides additional information about an element, usually displayed as a tooltip when hovering over the element.
    • Example: <img src="image.jpg" title="An example image">
  5. lang: Specifies the language of the element's content.
    • Example: <p lang="en">This is English text.</p>
  6. data-*: Allows embedding custom data attributes that can be accessed via JavaScript.
    • Example: <div data-user-id="12345">User Info</div>
  7. tabindex: Defines the tab order of an element when navigating with the Tab key.
    • Example: <input type="text" tabindex="1">
  8. aria-*: Used to improve accessibility for users with disabilities, providing information to assistive technologies.
    • Example: <button aria-label="Close" onclick="closeWindow()">X</button>
  9. hidden: Specifies that the element is not yet, or is no longer, relevant.
    • Example: <div hidden>Hidden content</div>
  10. accesskey: Defines a shortcut key to activate or focus an element.
    • Example: <button accesskey="s">Save</button>

Example Usage:

<div id="mainContent" class="container" title="Main Content Area" lang="en">
  <p style="color: red;">This is a paragraph.</p>
</div>


Global attributes are useful for adding functionality and enhancing the user experience across many types of elements.

72. How do you create a responsive design using HTML?

Creating a responsive design in HTML involves ensuring that the webpage adjusts and looks good on different screen sizes and devices. This is typically achieved using a combination of flexible layouts, CSS media queries, and responsive design principles.

Steps to Create a Responsive Design:

Use the meta tag for the viewport: The viewport meta tag ensures that the page scales properly on different devices, especially mobile ones.

<meta name="viewport" content="width=device-width, initial-scale=1.0">


Flexible Layout with CSS: Use relative units like percentages, em, rem, and vw (viewport width) for widths, padding, and margins, instead of fixed pixel values.

Example:

.container {
  width: 100%;
  padding: 20px;
  margin: 0 auto;
}


CSS Media Queries: Media queries allow you to apply different styles based on the screen size or device characteristics. For example, you can have a different layout for mobile devices, tablets, and desktops.
Example:

/* Default styles for desktops */
body {
  font-size: 16px;
}

/* Styles for devices with a max width of 768px (tablets) */
@media (max-width: 768px) {
  body {
    font-size: 14px;
  }


  .container {
    padding: 10px;
  }
}


/* Styles for devices with a max width of 480px (mobiles) */
@media (max-width: 480px) {
  body {
    font-size: 12px;
  }


  .container {
    padding: 5px;
  }
}


Flexible Images: Use max-width: 100% for images so they scale according to their container's width, avoiding overflow or distortion.

Example:

img {
  max-width: 100%;
  height: auto;
}

 

Responsive Grid Systems: You can use a responsive grid layout, such as CSS Grid or Flexbox, to create flexible column structures that adjust based on screen size.

Example with Flexbox

.container {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}


.box {
  width: 30%;
  margin: 10px;
}


@media (max-width: 768px) {
  .box {
    width: 45%;
  }
}


@media (max-width: 480px) {
  .box {
    width: 100%;
  }
}

Example of a Basic Responsive HTML Layout:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Responsive Design Example</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      margin: 0;
      padding: 0;
    }
    
    .container {
      display: flex;
      flex-wrap: wrap;
      padding: 20px;
    }


    .box {
      width: 30%;
      padding: 20px;
      margin: 10px;
      background-color: lightblue;
      text-align: center;
    }


    /* Tablet Layout */
    @media (max-width: 768px) {
      .box {
        width: 45%;
      }
    }


    /* Mobile Layout */
    @media (max-width: 480px) {
      .box {
        width: 100%;
      }
    }
  </style>
</head>
<body>
  <div class="container">
    <div class="box">Box 1</div>
    <div class="box">Box 2</div>
    <div class="box">Box 3</div>
  </div>


Output : 

Basic Responsive HTML Layout

73. Explain the purpose of the doctype declaration in HTML.

The DOCTYPE declaration in HTML is used to specify the version and type of HTML that a web document is written in. It is placed at the very beginning of the HTML document and informs the web browser about which rendering mode to use, ensuring proper interpretation of the page's code.

Purpose of the DOCTYPE Declaration:

  1. Document Type Definition (DTD): It specifies the rules and structure that the HTML document follows. For example, whether the document adheres to HTML5, HTML4, or XHTML standards.
  2. Browser Rendering Mode: The DOCTYPE helps browsers determine whether to render the page in "standards mode" (using the full HTML specification) or "quirks mode" (where older, non-standard behavior might be applied for backward compatibility).
  3. Ensuring Proper Formatting: Without the DOCTYPE declaration, browsers may use quirks mode, leading to inconsistent behavior and layout issues.

74. What is the difference between HTML5 and earlier versions of HTML?

The main differences between HTML5 and earlier versions of HTML (such as HTML 4.01 and XHTML) lie in features, syntax, and support for modern web standards. HTML5 was introduced to address the growing needs of modern web applications, including multimedia, mobile responsiveness, and rich user experiences.

Key Differences:

FeatureHTML5Earlier Versions (HTML 4.01 / XHTML)
Doctype Declaration<!DOCTYPE html> (simplified)<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" ...> (more complex)
Element SyntaxMore flexible; self-closing tags like <img> don't need closing slashes.Strict and verbose; <img /> requires a self-closing tag in XHTML.
Multimedia SupportBuilt-in support with <audio> and <video> elements.Requires third-party plugins (like Flash) for multimedia.
APIs and FeaturesSupports new APIs (Geolocation, Local Storage, Web Workers, Canvas).Limited API support; relies on JavaScript libraries or plugins.
Form ControlsNew controls (<input type="date">, <input type="email">), and attributes like placeholder.Fewer input types; relies heavily on JavaScript for functionality.
Semantic ElementsIntroduces semantic elements like <header>, <footer>, <section>, etc.Uses <div> and <span> for layout; lacks semantic elements.
CSS3 IntegrationFully integrates CSS3 features like transitions, animations, Flexbox.Limited CSS3 support; often requires workarounds.
Character EncodingUses UTF-8 by default.Requires specifying encoding explicitly in the <meta> tag.
CompatibilityHighly compatible with modern browsers and mobile devices.Less flexible and incompatible with newer devices or screen sizes.
Error HandlingLenient with errors; browsers render pages with mistakes.Stricter, especially in XHTML; documents must be well-formed.

75. What is the use of the target attribute in the <link> tag?

The target attribute is not typically used with the <link> tag. The <link> tag in HTML is primarily used for linking external resources like stylesheets, icons, and web app manifests. However, the target attribute is commonly used with the <a> (anchor) tag to specify how linked documents should be displayed.

Common Use of target Attribute:

For example, in the <a> tag:

  • target="_blank" opens the link in a new tab.
  • target="_self" (default) opens the link in the same tab.

The <link> Tag:

The <link> tag is used for referencing external resources like CSS files, icons, etc., and does not typically need or use the target attribute.

HTML5 Interview Questions and Answers

76. What is HTML5?

HyperText Markup Language 5(HTML5) is used to design web pages. A markup language is used to determine the text document within the tag, describing the structure of web pages. In contrast, we use HyperText to create a link between web pages. HTML5 is a combination of Markup and HyperText Language.

77. What is meant by HTML Entities?

HTML5 entities are special codes used for representing characters that have special meanings or they cannot be easily typed or displayed directly in HTML due to the conflicts with HTML tags. These entities are written with ampersand followed by a code, and then a semicolon. 

For example, the following entity code displays the ampersand symbol.

&amp;

78. Do HTML tags and elements refer to the same entities?

Tags are used for defining elements in HTML, they are not the same entities. Tags are simple text used for denoting the starting and ending of an HTML element.

For example, the '<p>' tag, defines the start of an HTML paragraph element, anything before the closing ‘</p>’ tag will be considered as the content of the paragraph element.

<p>This is a paragraph</p>

79. What is meant by ‘class’ attribute in HTML?

The class attribute is used for assigning one or more class names to an HTML element. The value of the class attribute is a space-separated list of class names. Unlike ids, a class name can be assigned to more than 1 element. They are used for styling HTML elements with CSS and selecting DOM nodes with JavaScript.

80. What is multipart form data in HTML?

In HTML5, “multipart/form-data” is an encoding type used for forms when you want to upload files. When a form is submitted with the multipart/form-data encoding type, the form data is divided into multiple parts, allowing files to be uploaded to your backend services.

81. What are tags in HTML5?

Tags in HTML5 are used to define the structure and content of a web page. They are enclosed in angle brackets (< >) and come in pairs, with an opening tag and a closing tag. For example, the <p> tag is used to define a paragraph, and the <img> tag is used to define an image.

82. List some new tags in HTML5.

New list of tags are added in HTML5 to provide document a better structure. primary component of HTML. A tag mainly consists of three components,

  • <article>
  • <aside>
  • <mark>
  • <video>
  • <svg>
  • <rt>

83. What are void tags in HTML5?

This is one of the most commonly asked and the easiest HTML5 Interview Questions. The HTML tags that don’t require a closing or ending tag are known as void tags, for example, <br>, <hr>, <img>, etc.

84. What are the attributes in HTML5?

Attributes are additional conditions added to a tag to add more specific instructions to the content. HTML5 attributes are case insensitive and may be written in all uppercase or mixed case. For example, <div class = "example">...</div>, which illustrates how to mark up a div element with an attribute named class using a value of "example".

85. How many tags were removed in HTML5?

The list of the tags that are removed completely in HTML5 include:

  • <frame>
  • <frameset>
  • <noframes>
  • <big>
  • <basefront>
  • <applet>
  • <center>
  • <bigcenter>
  • <acronym>
  • <basefont>
  • <dir>
  • <tt>
  • <font>
  • <strike>

86. How does HTML5 handle offline web applications? Discuss the role of the manifest attribute.

HTML5 provides support for offline web applications through the Application Cache feature, which uses the manifest attribute in the <html> tag. This allows web pages to be cached on the user's device, enabling them to be accessed even when the user is offline.

Role of the manifest Attribute:

  • The manifest attribute links an HTML file to a cache manifest file. This file lists the resources (e.g., HTML, CSS, JavaScript, images) to be cached for offline use.

Example:

<!DOCTYPE html>
<html manifest="offline.appcache">
  <head>
    <title>Offline App</title>
  </head>
  <body>
    <h1>Welcome to my offline web application!</h1>
  </body>
</html>


Cache Manifest File (offline.appcache):

CACHE MANIFEST
# v1.0
index.html
styles.css
app.js
logo.png


NETWORK:
*


How It Works:

  • When the user visits the page, the browser downloads and stores the resources specified in the manifest file.
  • The application is available offline as long as the manifest file is valid and the resources are cached.

87. What is a polyfill, and how is it relevant to HTML5 features? Provide an example of a scenario where a polyfill is necessary

polyfill is a piece of code (usually JavaScript) that provides functionality for features not natively supported by certain web browsers. Polyfills enable developers to use newer HTML, CSS, or JavaScript features in older browsers, ensuring compatibility and consistent behavior across different environments.

Relevance to HTML5 Features:

Many HTML5 features, such as new form elements, APIs (e.g., localStorage, geolocation), or <video> and <audio> tags, may not be supported in older browsers. Polyfills provide a way to replicate these features in browsers that don't support them, allowing developers to use modern web technologies while maintaining backward compatibility.

Example Scenario: <audio> Element Support

The <audio> element in HTML5 allows embedding audio files directly into web pages. However, older browsers like Internet Explorer 8 or below don't support this element. A polyfill can be used to enable audio playback in these browsers.

Example of a Polyfill for <audio>:

<script>
  if (!document.createElement('audio').canPlayType) {
    // Polyfill code to add audio support in browsers that don't support <audio>
    // For example, using Flash to play audio files
    document.write('<object data="audio-player.swf" type="application/x-shockwave-flash"></object>');
  }
</script>


In this case:

  • The polyfill checks if the browser supports the <audio> element by testing the canPlayType method.
  • If the browser doesn't support <audio>, it loads a Flash-based audio player instead.

When is a Polyfill Necessary?

Polyfills are necessary when:

  • You want to use newer web features (like HTML5 elements, CSS3 properties, or JavaScript APIs) but need to support older browsers that lack native support.
  • They ensure that your web app works consistently across a wider range of devices and browsers, improving accessibility and user experience.

88. Explain the <canvas> element in HTML5. How does it differ from the <svg> element in terms of rendering and use cases?

The <canvas> element in HTML5 is used to draw graphics, such as shapes, images, and animations, dynamically via JavaScript. It provides a 2D drawing context where developers can render pixel-based images, shapes, and other graphics.

Key Features of <canvas>:

  • It’s a bitmap-based rendering system.
  • It is used for drawing dynamic, interactive graphics like games, animations, and data visualizations.
  • Unlike static images, the content drawn on a <canvas> is not part of the document's DOM. It is created and manipulated using JavaScript.

Example:

<canvas id="myCanvas" width="500" height="500"></canvas>
<script>
  const canvas = document.getElementById('myCanvas');
  const ctx = canvas.getContext('2d');
  ctx.fillStyle = 'red';
  ctx.fillRect(50, 50, 150, 100); // Draws a red rectangle
</script>


OUTPUT

canvas element in html5

<svg> Element:

  • The <svg> (Scalable Vector Graphics) element is used to create vector-based graphics. It defines graphics in XML format and is part of the DOM.
  • It’s suitable for graphics that need to be scaled without losing quality, such as icons, logos, and simple animations.

Differences Between <canvas> and <SVG>:

Feature<canvas><svg>
RenderingBitmap-based: Draws pixels on a grid.Vector-based: Uses XML to define shapes.
ManipulationManipulated dynamically via JavaScript.DOM elements can be directly manipulated via JavaScript.
Use CasesInteractive graphics, games, animations, complex data visualizations.Static images, scalable graphics like icons, logos, and simple animations.
PerformanceEfficient for complex, real-time rendering (like games).Better for simpler graphics with more interactivity (like vector illustrations).
ScalabilityQuality degrades when scaled (pixel-based).Scales infinitely without losing quality (vector-based).
DOM IntegrationThe content is not part of the DOM and cannot be accessed by CSS directly.Elements are part of the DOM and can be styled with CSS.
ComplexityMore complex to implement for detailed images or animations.Easier for simpler, static graphics but limited for complex dynamic rendering.

When to Use <canvas>:

  • When you need to create dynamic, real-time graphics (e.g., games, simulations, or complex charts).
  • For pixel-based graphics where precise manipulation of every pixel is needed (e.g., image editing apps).

When to Use <svg>:

  • For static graphics or simple animations like logos, icons, and illustrations that need to be scalable.
  • When you want to manipulate individual shapes (e.g., a line, circle, or path) through JavaScript or CSS.
  • For responsive graphics that scale well without losing quality.

89. Explain the concept of the contenteditable attribute in HTML5. What are the limitations and best practices for using it? 

The contenteditable attribute in HTML5 allows you to make any HTML element editable by the user directly in the browser. When set to true, this attribute enables the user to interact with the content of the element, modifying it as if it were a text editor.

Key Features of contenteditable:

  • Enables in-place editing: Users can click and type within an element, making changes to its content without needing external tools.
  • Works on most HTML elements: You can apply contenteditable to most elements, such as <div>, <span>, and <p>, allowing them to become editable areas.

Example:

<div contenteditable="true">
  This is an editable text area. You can modify the text here.
</div>


In this case, the text inside the <div> becomes editable by the user. They can click and change the text.

Limitations of contenteditable:

  1. Limited control over formatting:
    • When users edit content, the browser may apply formatting (such as inline styles), which might not be desirable for all use cases.
    • For instance, users could inadvertently introduce unclean HTML or unwanted styles, especially if they copy-paste content from other sources.
  2. No built-in validation:
    • There is no validation or restriction of content by default. You have to manually implement logic to ensure that the content meets specific requirements (e.g., restrict certain HTML tags, sanitize input).
  3. Browser inconsistencies:
    • Different browsers may behave differently with the contenteditable attribute, leading to inconsistencies in how content is edited and rendered across platforms.
  4. Security Concerns:
    • Allowing users to edit content directly in the DOM can lead to potential security issues (e.g., XSS attacks) if the content is not sanitized before being saved or used in other parts of the application.
  5. Complexity with complex interactions:
    • For complex text-editing features (like rich text editors), contenteditable can be difficult to manage and may not provide the flexibility needed without implementing additional JavaScript or libraries.

90. What is the purpose of the sandbox attribute in the <iframe> element? How does it enhance security?

The sandbox attribute in the <iframe> element is used to enhance the security of content loaded within an iframe by restricting its behavior. When applied, it imposes a set of limitations on the iframe’s content, effectively isolating it from the parent page to prevent malicious actions and protect against potential security risks.

Purpose of the sandbox Attribute:

The primary purpose of the sandbox attribute is to add a layer of security by restricting the iframe’s ability to perform certain actions that could be potentially harmful, such as executing scripts, navigating the parent page, or submitting forms.

How It Enhances Security:

When the sandbox attribute is used without any values, it applies the following restrictions to the iframe content:

  • JavaScript execution: Disables JavaScript execution within the iframe.
  • Form submission: Disables form submissions (prevents form data from being sent from the iframe).
  • Pop-ups: Prevents the iframe from opening new browser windows or tabs (e.g., no window.open).
  • Navigation: The iframe cannot navigate the top-level browsing context (parent page), which means it cannot change the parent page’s location.
  • Plugins: Disables plugins such as Flash or Java applets from running.
  • Same-origin policy enforcement: Enforces the same-origin policy, preventing the iframe from accessing content outside its origin.

Conclusion

In this article, we have discussed the top HTML interview questions and answers. We hope that this blog has helped you to prepare for your next html interview. Also check out some of our amazing articles such as HTML5, Data Structures and Algorithms, Programming Fundamentals, Web Technologies, and many more.

Live masterclass