HTML Interview Questions

Master your next HTML interview with our comprehensive collection of questions and expert-crafted answers. Get prepared with real scenarios that top companies ask.

Find mentors at
Airbnb
Amazon
Meta
Microsoft
Spotify
Uber

Master HTML interviews with expert guidance

Prepare for your HTML interview with proven strategies, practice questions, and personalized feedback from industry experts who've been in your shoes.

Thousands of mentors available

Flexible program structures

Free trial

Personal chats

1-on-1 calls

97% satisfaction rate

Study Mode

Choose your preferred way to study these interview questions

1. What is HTML Semantic? And why is it important?

HTML Semantic essentially refers to the use of HTML markup to reinforce the semantics or meaning of the content. In other words, it's the use of HTML tags in a way that reflects the type of content they enclose. For instance, tags like <header>, <nav>, <footer>, and <article> are semantic because they accurately describe the type and purpose of the content they contain.

Semantic HTML is important both for accessibility and for SEO. It helps assistive technologies like screen readers understand the content, improving access for users with disabilities. For search engines, it provides clear context and meaning which can affect how the page is indexed and ranked. Additionally, semantic markup enhances the maintainability of the site, making it easier for developers to understand and work with.

2. What is HTML and why do we use it?

HTML stands for HyperText Markup Language. It is the standard markup language used to structure content on a web page.

I usually explain it like this:

  • HTML gives a page its skeleton
  • It defines things like headings, paragraphs, links, images, forms, tables, and sections
  • Browsers read HTML and turn it into the page you see on screen

Why we use it:

  • It creates the basic structure of every website
  • It helps browsers understand and display content correctly
  • It makes content more meaningful with semantic tags like header, article, and footer
  • It works together with CSS and JavaScript, HTML handles structure, CSS handles styling, JavaScript handles behavior

So in simple terms, HTML is the foundation of the web. Without it, there is no organized content for a browser to render.

3. Can you briefly explain what doctype is?

DOCTYPE is the declaration at the very top of an HTML file.

What it does: - Tells the browser how to interpret the document - Puts the page into standards mode - Helps browsers render the page consistently

For modern HTML, it’s just: <!DOCTYPE html>

A couple of important notes: - It is not an HTML element - In HTML5, it’s very simple and mostly there to trigger proper browser behavior, not to reference a complex DTD like older HTML versions did

So in plain English, it’s basically the browser’s cue to say, “render this page using normal modern HTML rules.”

No strings attached, free trial, fully vetted.

Try your first call for free with every mentor you're meeting. Cancel anytime, no questions asked.

Nightfall illustration

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

In HTML, an element is the combination of a starting tag, its attributes, the content between the tags, and an ending tag. For example, in <p>Hello World!</p>, the whole thing is considered an "element" - including the opening tag, the content, and the closing tag.

On the other hand, a tag is used to mark the start or end of an element. There are opening tags like <p> and closing tags like </p>. In our earlier example <p>Hello World!</p>, <p> is the opening tag and </p> is the closing tag. Tags can also contain attributes to provide additional information about the element.

So, in essence, tags form the beginning and end of an element in HTML.

5. How would you comment lines in HTML?

To comment lines in HTML, you use the <!-- --> syntax. Anything placed between these symbols will be considered as a comment by the browser and won't be rendered on the webpage. For example, if you want to comment out a line, you'd write <!-- This is a comment -->. You can also use this syntax to comment out blocks of code, meaning multiple lines, by placing all the lines between the opening <!-- and closing -->. Comments help developers understand the code better or to temporarily deactivate certain parts of HTML without deleting them.

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

The id and class attributes in HTML are used to assign identifiers to elements. Both are often used in conjunction with CSS or JavaScript to manipulate or style the elements.

The key difference is uniqueness and usage. An id is unique within a page and should be used only once, while a class can be applied to multiple elements. For example, if you have a specific style that needs to be applied just to one element, you would use an id. But if a style should be spread across many elements, you would use a class.

For instance, in CSS, IDs are referenced using a hash (#) symbol followed by the ID name, like #uniqueElement {...}. For classes, a dot (.) is used, like .multipleElements {...}.

Moreover, because IDs are unique, they have a higher specificity in CSS, meaning rules applied by IDs will override those set by classes if there's a conflict.

7. Explain the use and process of nesting HTML elements.

Nesting in HTML just means putting one element inside another to create structure.

A simple example is a paragraph inside a div: <div><p>This is a paragraph.</p></div>

What matters is the relationship:

  • The div is the parent
  • The p is the child
  • Together they form part of the page hierarchy

Why nesting matters:

  • It gives the page a clear structure
  • It helps browsers understand how to render content
  • It makes styling with CSS and targeting with JavaScript much easier
  • It supports accessibility and semantic meaning when you use the right elements

The process is pretty straightforward:

  1. Open the parent element
  2. Place the child element inside it
  3. Close the child element
  4. Close the parent element

So the order should be: - Correct: <section><p>Text</p></section> - Incorrect: <section><p>Text</section></p>

A few important rules:

  • Close inner elements before outer elements
  • Only nest elements where they are valid according to HTML rules
  • Use semantic elements when possible, like header, article, nav, and footer, instead of relying on generic divs everywhere

If nesting is done wrong, browsers may try to fix it for you, but the layout, accessibility, or behavior can become inconsistent.

8. How would you create a hyperlink in HTML?

You create a hyperlink with the anchor tag, a.

Basic format: - Use href to set where the link goes - Put the clickable text between the opening and closing tags

Example: - <a href="https://www.google.com">Go to Google</a>

A couple of common cases: - External link: href="https://example.com" - Internal page: href="about.html" - Section on the same page: href="#contact"

So the main idea is simple: - href = destination - Link text = what the user clicks

User Check

Find your perfect mentor match

Get personalized mentor recommendations based on your goals and experience level

Start matching

9. How would you insert an image in HTML?

You add an image in HTML with the img tag.

The two main attributes are:

  • src, the path or URL to the image
  • alt, a text description for accessibility and fallback

Example:

<img src="myimage.jpg" alt="A description of the image">

A few quick notes:

  • src can be a relative path like images/photo.jpg
  • or a full URL like https://example.com/photo.jpg
  • alt is important for screen readers and if the image does not load

If I were answering in an interview, I’d keep it simple and mention best practice too:

  • Use img to embed the image
  • Set src to the image location
  • Always include meaningful alt text

10. What is the importance of using an HTML validator?

Using an HTML validator matters because it catches problems early, before they turn into browser bugs or accessibility issues.

A validator helps with things like:

  • Missing or unclosed tags
  • Incorrect nesting
  • Invalid attributes
  • Duplicate IDs
  • Outdated or nonstandard markup

Why that matters in practice:

  • Better cross-browser consistency, valid HTML is more predictable
  • Easier debugging, you spend less time chasing weird layout issues
  • Stronger accessibility, semantic and valid markup works better with screen readers
  • Cleaner codebase, which makes maintenance easier for the whole team
  • Better SEO foundation, search engines handle clean, structured markup more reliably

I would not say validation guarantees performance or rankings by itself, but it does help create a solid, standards-based site that is easier for browsers, assistive tech, and search engines to process.

I usually see it as a quality check, not just a rule checker. It helps keep the HTML clean, professional, and dependable.

11. How would you use a tag to create a new line in HTML?

Use the <br> tag.

A few key points:

  • <br> inserts a line break
  • It’s a void element, so there’s no closing tag
  • Best for content where the line break actually matters, like:
  • addresses
  • poems
  • song lyrics

Example:

<p>Roses are red,<br>Violets are blue,<br>HTML is easy,<br>And fun too!</p>

One important note:

  • Don’t use <br> just to add visual spacing in a layout
  • For spacing and structure, use CSS instead

12. What is the use of the <canvas> tag in HTML5?

The <canvas> tag in HTML5 gives you a drawable area on the page.

You use it when you want to render graphics with JavaScript, like:

  • shapes and charts
  • animations
  • image manipulation
  • game graphics
  • custom visual effects

A couple of important points:

  • <canvas> itself is just a container
  • it does not draw anything on its own
  • JavaScript is what actually draws on it, usually through the 2D API or WebGL

Typical setup:

  • add a <canvas> element
  • give it width and height
  • target it in JavaScript with something like getContext("2d")

It also supports fallback content. So if a browser does not support <canvas>, the text inside the tag can be shown instead.

In short, <canvas> is used for dynamic, script-driven graphics in the browser.

13. Can you discuss two types of lists we can create using HTML and their syntax?

Two common HTML list types are:

  1. Unordered list
  2. Ordered list

Unordered list - Used when the order does not matter - Displays bullet points by default - Built with <ul> - Each item uses <li>

Example: Use <ul> as the wrapper, then add items like <li>Apple</li>, <li>Banana</li>, and <li>Cherry</li> inside it.

Ordered list - Used when the sequence does matter - Displays numbers by default - Built with <ol> - Each item still uses <li>

Example: Use <ol> as the wrapper, then add items like <li>Step one</li>, <li>Step two</li>, and <li>Step three</li> inside it.

Quick syntax pattern - Unordered: <ul> + multiple <li> items + </ul> - Ordered: <ol> + multiple <li> items + </ol>

The key difference is simple: - <ul> = bullets - <ol> = numbered or ordered steps

14. How do you embed a YouTube video on an HTML page?

The usual way is to use a YouTube iframe embed.

Quick process:

  1. Open the video on YouTube
  2. Click Share
  3. Click Embed
  4. Copy the iframe code YouTube gives you
  5. Paste it into your HTML where you want the video to appear

A typical embed looks like:

<iframe width="560" height="315" src="https://www.youtube.com/embed/VIDEO_ID" title="YouTube video player" allowfullscreen></iframe>

A few key parts:

  • src, points to the YouTube embed URL
  • width and height, control the player size
  • title, helps with accessibility
  • allowfullscreen, lets users expand the video fullscreen

If I want it to be more production-friendly, I usually also make it responsive with CSS so it scales nicely on mobile, instead of relying on fixed width and height.

15. Can you tell me different ways to incorporate CSS into an HTML file?

There are 3 common ways to add CSS to an HTML page:

  1. Inline CSS
  2. Add styles directly on an element with the style attribute
  3. Example: p style="color: blue;"

Best for: - Quick tests - One-off styling

Downside: - Hard to maintain - Mixes content and presentation - Not ideal for real projects

  1. Internal CSS
  2. Put styles inside a <style> tag in the <head>
  3. Example: define something like p { color: blue; } there

Best for: - Small projects - Single-page demos - Page-specific styles

Downside: - Not reusable across multiple pages

  1. External CSS
  2. Link a separate .css file using a <link> tag in the <head>
  3. Example: link rel="stylesheet" href="styles.css"

Best for: - Most real websites - Reusable, scalable styling - Keeping HTML clean

Why it’s preferred: - Easier to manage - Better organization - One stylesheet can serve multiple pages

If I were answering in an interview, I’d keep it simple: inline for quick overrides, internal for small page-level styling, and external CSS for most production use cases.

16. Can you explain about HTML escape characters?

HTML escape characters, also known as HTML entities, are used to display reserved characters in HTML that would otherwise be interpreted differently by the browser.

For instance, if you try to use a less than or greater than symbol (< or >) in your HTML, the browser might interpret it as an opening or closing HTML tag. To avoid this, you can use escape characters or entities. So, instead of < and >, you'd use &lt; and &gt; respectively in your HTML.

Another common use case is for displaying special characters that are not readily available on the keyboard, such as copyright symbol (©), which can be represented as &copy;.

One more noteworthy entity is &amp; which represents an ampersand. An actual ampersand (&) in your HTML can be mistaken as the start of an escape character, so it's best to use &amp; when you want to display an ampersand.

So, in general, HTML escape characters ensure that the characters are displayed as intended and not mistaken for HTML tags or other entities.

17. How do you handle multilingual HTML content?

I handle multilingual HTML by treating language, encoding, and accessibility as the basics from day one.

A solid answer usually covers 3 things:

  1. How the page declares language
  2. How text is encoded and rendered correctly
  3. How the overall site supports multiple locales

In practice, I’d say:

  • Set the main document language with the lang attribute on the <html> element, like lang="en" or lang="es".
  • If only part of the page changes language, I add lang to that specific element so browsers and screen readers interpret it correctly.
  • Always use meta charset="UTF-8" so characters from different languages display properly.
  • Keep content separate from markup when possible, so translations are easier to manage and update.
  • For larger sites, I usually pair the HTML setup with a localization strategy, things like locale-specific routes, translated content files, and sometimes language detection based on user preference.

I also pay attention to usability details:

  • Make sure screen readers pronounce content correctly
  • Support right-to-left languages when needed with dir="rtl"
  • Avoid hardcoding text in components if the site will scale across languages
  • Test layouts for text expansion, because some languages take much more space than English

A simple example would be an English page with a French quote inside it. I’d keep the page as lang="en" and mark just the quote with lang="fr". That helps both accessibility tools and search engines understand the content properly.

18. Can you list the new form elements in HTML5?

The main new HTML5 form-related elements are:

  • <datalist>
  • Pairs with an <input> to show suggested values.
  • Useful for autocomplete-style dropdown suggestions.

  • <output>

  • Displays the result of a calculation or user action.
  • Often used with JavaScript in interactive forms.

  • <progress>

  • Shows how far a task has completed.
  • Good for uploads, loading states, or multi-step actions.

  • <meter>

  • Represents a value within a known range.
  • Common for things like scores, storage usage, or ratings.

It’s also worth mentioning that HTML5 expanded forms a lot through new input types, even though they are not separate elements.

Examples include:

  • email
  • url
  • tel
  • number
  • range
  • date
  • time
  • month
  • week
  • datetime-local
  • color
  • search

Why that matters:

  • Better built-in validation
  • Better mobile keyboards
  • Better user experience with less custom JavaScript

If I were answering this in an interview, I’d mention both: 1. The new form elements 2. The new input types, because both were big HTML5 form improvements

19. How would you make a checkbox appear checked by default?

To make a checkbox appear checked by default when the page loads, you can use the checked attribute in the <input> tag. Here's an example:

html <input type="checkbox" checked>

In this example, the checked attribute specifies that the checkbox should be preselected when the page loads. Note that there's no value after checked. This is a boolean attribute, which means its presence alone makes it true. If you want the checkbox to not be checked by default, you would simply leave the attribute out altogether.

20. What does a viewport meta tag do in HTML?

The viewport meta tag in HTML is a way to control how your webpage scales on different sized devices to ensure it's optimized for all screen sizes. It's a critical part of making your site mobile-friendly.

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

In this common example, width=device-width makes the width of the webpage follow the screen-width of the device (which will vary depending on the device). The initial-scale=1 part sets the initial zoom level when the page is first loaded by the browser.

Without a viewport meta tag, mobile devices render pages at typical desktop screen widths, and then try to make the content look better by increasing font sizes and scaling the content to fit the screen. This often results in problematic layout for the page if it wasn't designed with this kind of scaling in mind. The viewport meta tag helps to avoid these issues, providing users with a better and more consistent browsing experience.

21. Explain the importance of "required" attribute in terms of form validation in HTML.

The required attribute in HTML is used in form input elements to enforce that a field must be filled out before the form can be submitted. As a part of built-in form validation in HTML, it helps ensure that important data is not missing when the form data is processed.

For example, if you have an input field for an email address which is important for your form, you could make it a required field like so:

html <input type="email" name="email" required>

In this example, if users attempt to submit the form without providing an email address, the browser will highlight the field and display a message indicating that input is required. The user will then need to fill in that field before they can successfully submit the form.

This attribute offers a simple, client-side method of ensuring you receive necessary data, without needing extra JavaScript or server-side validation to enforce it (though, note that server-side validation remains important for security, as client-side validation is not foolproof).

22. What's the purpose of "data-*" attributes in HTML?

data-* attributes are for attaching custom, non-visible information to an HTML element in a valid, standards-based way.

A simple way to think about it:

  • HTML gives you built-in attributes like id, class, and href
  • data-* lets you add your own metadata when none of the built-in ones fit

Example:

  • <div data-product-id="1234">...</div>

In JavaScript, you can read it with dataset:

  • element.dataset.productId

Why they’re useful:

  • Store IDs, states, or config values right on the element
  • Make it easier for JavaScript to connect behavior to markup
  • Avoid misusing class or id just to hold data

Common use cases:

  • Product IDs
  • Tracking info
  • UI state like data-open="true"
  • Filtering and sorting values

One important note, they’re meant for small bits of page-related metadata, not as a place to dump large application data or sensitive info.

23. What is the use of the 'alt' attribute in HTML?

The alt attribute gives an image a text alternative.

Why it matters:

  • Accessibility, screen readers read the alt text so users who cannot see the image still get the meaning.
  • Fallback, if the image does not load, the alt text appears instead.
  • SEO and semantics, it also helps search engines understand what the image is about.

Example:

<img src="team-photo.jpg" alt="Marketing team standing in the office">

A couple of best practices:

  • Be specific and describe the image clearly.
  • Keep it short if possible.
  • If the image is purely decorative, use alt="" so screen readers skip it.

24. Explain the concept of lazy loading in HTML.

Lazy loading is a strategy used to delay the loading of resources until they are needed, rather than loading all resources upfront when a page loads. This can significantly improve performance and reduce data usage by only loading content as it's required.

In HTML, lazy loading is often applied to images and iframes. With the introduction of native lazy loading in modern browsers, you can simply add the loading attribute to your <img> or <iframe> tag with the value "lazy". For example:

html <img src="image.png" loading="lazy" alt="My Image">

In this instance, the browser will wait to load "image.png" until the user scrolls near it. If the browser does not support the loading attribute, it will just ignore it and the resource will load normally, so it does not break anything for users on unsupported browsers.

Prior to native lazy loading, developers had to rely on JavaScript libraries such as Lozad.js or LazyLoad to achieve this functionality.

25. How do you improve HTML performance?

I usually think about HTML performance in one simple way, get meaningful content on screen fast, with as little blocking as possible.

A few things I focus on:

  • Keep the HTML lean
  • Remove unnecessary wrappers and deeply nested elements.
  • Use semantic tags like header, main, section, instead of extra divs everywhere.
  • Smaller, cleaner markup is faster to parse and easier to maintain.

  • Reduce render-blocking resources

  • Load critical CSS first.
  • Use defer for scripts that do not need to run immediately.
  • Avoid putting blocking JavaScript in the head unless it is truly required.

  • Load less upfront

  • Lazy load images and iframes with loading="lazy".
  • Compress images and serve the right size for the device.
  • Do not ship hidden or offscreen content if it is not needed right away.

  • Cut down requests and payload size

  • Minify HTML, CSS, and JavaScript.
  • Remove unused CSS and JS.
  • Use caching, compression like Gzip or Brotli, and a CDN when appropriate.

  • Prioritize perceived performance

  • Make above-the-fold content available first.
  • Set explicit image dimensions to avoid layout shifts.
  • Preload important assets like fonts or hero images only when there is a clear benefit.

  • Write HTML that helps the browser

  • Use responsive images with srcset and sizes.
  • Add width and height on images.
  • Avoid large DOM trees, because they increase style and layout work.

If I had to boil it down, I would say performance improves when the browser has less to download, less to parse, and less to block rendering.

26. What is the significance of a Title Tag in HTML?

The HTML title tag matters for both users and search engines.

Here’s why it’s important:

  • It sets the page title shown in the browser tab
  • It often appears as the clickable headline in search results
  • It helps people quickly understand what the page is about
  • It gives search engines a strong signal about the page content

Example:

  • If your page has <title>My First Web Page</title>, that text usually shows in the tab and may also be used in search listings

Best practice is to make every page title:

  • Clear
  • Specific
  • Relevant to the page
  • Short enough to read easily

So, it’s not just a label, it’s a key part of usability, accessibility, and SEO.

27. How do you resize an image in HTML?

You can resize an image right in the <img> tag by setting width and/or height.

  • Example: <img src="myimage.jpg" alt="My image" width="300">
  • You can also set both: <img src="myimage.jpg" alt="My image" width="300" height="200">

A couple of best practices:

  • If you set both width and height, make sure they match the image’s original proportions, otherwise it can look stretched.
  • If you want to keep the aspect ratio safe, set just one, usually width, and let the browser calculate the other automatically.
  • In modern projects, CSS is often the cleaner option for resizing, especially for responsive layouts. For example, setting the image width in CSS and using height: auto.

So the short answer is, use width and height on the <img> element, but be careful not to distort the image.

28. How do you create a table in HTML?

To create a table in HTML, you use a few core tags:

  • <table> defines the table
  • <tr> creates a row
  • <th> creates a header cell
  • <td> creates a data cell

A simple structure looks like this:

  • Start with <table>
  • Add a row with <tr>
  • Put headers inside that row with <th>
  • Add more <tr> rows for the actual data
  • Use <td> inside those rows for each cell

Example structure:

<table> <tr><th>Name</th><th>Role</th></tr> <tr><td>Alice</td><td>Developer</td></tr> <tr><td>Bob</td><td>Designer</td></tr> </table>

A couple of best practices:

  • Use <th> for column headings, not just bold text
  • Keep layout styling in CSS, not in old HTML attributes like border
  • If the table is more complex, you can also use <thead>, <tbody>, and <caption> for better structure and accessibility

So really, it’s just rows inside a table, with headers and data cells placed in the right spots.

29. What types of SEO meta tags are there in HTML?

The main SEO-related tags in HTML fall into a few practical buckets:

  1. Core search result tags
  2. title
  3. Not a meta tag, but one of the most important SEO elements.
  4. It shows up in the browser tab and often in search results.
  5. meta name="description"
  6. Gives a short summary of the page.
  7. It does not usually improve rankings directly, but it can improve click-through rate.

  8. Crawling and indexing tags

  9. meta name="robots"
  10. Tells search engines what they can do with the page.
  11. Common values: index, noindex, follow, nofollow.
  12. meta name="googlebot"
  13. Same idea, but targeted specifically at Google’s crawler.

  14. Canonical and duplicate content control

  15. link rel="canonical"
  16. Also not a meta tag, but very important for SEO.
  17. It tells search engines which URL is the preferred version of a page.

  18. Social sharing tags that support visibility

  19. Open Graph tags like meta property="og:title" and meta property="og:description"
  20. Mainly used for Facebook, LinkedIn, and other platforms.
  21. Not direct ranking factors, but they affect how links look when shared.
  22. Twitter Card tags like meta name="twitter:title"
  23. Same idea, but for X and similar previews.

  24. Technical meta tags that indirectly help SEO

  25. meta charset="UTF-8"
  26. Helps browsers render text correctly.
  27. meta name="viewport"
  28. Important for mobile responsiveness, which matters for SEO and usability.

  29. Tags with little or no SEO value today

  30. meta name="keywords"
  31. Historically used for keywords.
  32. Most major search engines ignore it now because it was heavily abused.

If I were answering this in an interview, I’d keep it simple: mention title, description, robots, and canonical first, then add Open Graph, Twitter Cards, and viewport as supporting tags. That shows you know both direct SEO signals and the tags that improve how pages are displayed and shared.

30. How would you open a link in a new browser window?

Use the target attribute on the anchor tag.

  • Set target="_blank" to open the link in a new tab or window, depending on the browser.
  • Example: <a href="https://www.example.com" target="_blank">Visit Example</a>

One important best practice:

  • Add rel="noopener noreferrer" when using _blank for security and performance.

So the safer version is:

<a href="https://www.example.com" target="_blank" rel="noopener noreferrer">Visit Example</a>

Small note, whether it opens in a new tab or a new window is usually controlled by the user's browser settings.

31. What are the main elements of an HTML5 page structure?

The main HTML5 page structure is pretty straightforward. I usually think of it in two layers, the document shell, and the semantic sections inside the page.

  1. Document shell
  2. <!DOCTYPE html> sets the document as HTML5
  3. <html> is the root element for the whole page
  4. <head> holds metadata, like:
  5. character set
  6. viewport settings
  7. page title
  8. linked CSS or scripts
  9. <body> contains everything the user actually sees

  10. Semantic layout elements inside <body> HTML5 introduced semantic tags so the page structure is clearer for both developers and browsers.

  11. <header> for the top section of a page or section

  12. <nav> for navigation links
  13. <main> for the primary content of that page
  14. <section> for grouping related content
  15. <article> for standalone content, like a blog post or news item
  16. <aside> for side content, like a sidebar or related links
  17. <footer> for closing info, copyright, or contact links

A simple mental model is: - head = page info - body = visible content - semantic tags = meaningful layout inside the body

If I were building a basic page, it would usually be organized as: <!DOCTYPE html><html><head><body><header>, <nav>, <main>, <aside>, <footer>

That structure makes the page easier to read, maintain, and make accessible.

32. What are some new semantic elements added in HTML5?

HTML5 added a bunch of semantic tags that make page structure much clearer, both for developers and for assistive tech.

Some of the big ones are:

  • <header>
  • Intro content for a page or a section
  • Often holds a logo, title, search, or nav

  • <footer>

  • Closing content for a page or section
  • Common for copyright, contact info, related links

  • <nav>

  • A block of major navigation links
  • Best for primary menus, not every random link list

  • <main>

  • The main content of the page
  • Should be unique on the page

  • <article>

  • Self-contained content that can stand on its own
  • Think blog posts, news articles, forum entries

  • <section>

  • A thematic grouping of content
  • Usually has its own heading

  • <aside>

  • Secondary content related to the main content
  • Like sidebars, callouts, or related links

  • <figure> and <figcaption>

  • For media or visuals plus their caption
  • Useful for images, charts, diagrams, code samples

A simple way to explain why they matter:

  • They make markup easier to read
  • They improve accessibility and document structure
  • They help browsers, screen readers, and search engines understand the content better

One important point, semantic tags are about meaning, not styling. You use <section> or <article> because of what the content is, not because of how you want it to look.

33. Can you differentiate between inline and block-level elements?

Block-level and inline elements mainly differ in how they flow on the page.

  • Block-level elements start on a new line
  • They usually take up the full available width
  • They are used for larger structural sections of content

Examples: - <div> - <p> - <h1> to <h6> - <section> - <article>

Inline elements stay within the same line of content.

  • They do not start on a new line
  • They only take up as much space as they need
  • They are usually used for small pieces of content inside a block

Examples: - <span> - <a> - <strong> - <em> - <img>

A simple way to think about it:

  • Block elements structure the page
  • Inline elements style or mark up content within that structure

One important detail, CSS can change this behavior with the display property. For example, a <div> can be made inline, and a <span> can be made block. But semantically, it is still best to choose the element based on meaning first, then use CSS for layout.

34. Can you discuss about creating a drop-down list in HTML?

A drop-down list in HTML is usually built with the select element and a set of option elements.

Basic idea:

  • select is the dropdown itself
  • option is each item inside it
  • name is important when the field is submitted in a form
  • value is the actual data sent to the server
  • The visible text is what the user sees

Example structure:

  • select name="pets"
  • inside it:
  • option value="dog" shows Dog
  • option value="cat" shows Cat
  • option value="rabbit" shows Rabbit

If the user picks Dog, the submitted value is dog.

A few useful things to mention in an interview:

  • Use selected to make one option the default
  • Use disabled if an option should not be selectable
  • Use multiple if users should be able to choose more than one item
  • Use optgroup to organize long lists into categories
  • Pair it with a label for accessibility

For example, a good accessible setup is:

  • a label connected to the select
  • a default placeholder-style option like Select a pet
  • meaningful value attributes

One important point, if you need a searchable or highly customized dropdown, plain HTML select has limits. In that case, people often enhance it with JavaScript or a UI library, but the native select is still the simplest and most semantic starting point.

35. How do ARIA roles and attributes complement native HTML, and when should you avoid using them?

ARIA is there to fill accessibility gaps, not to replace good HTML.

The core idea

Native HTML already has built-in semantics.

  • <button> is a button
  • <a href="..."> is a link
  • <input> is a form control
  • <nav>, <main>, <header> give landmark meaning

Browsers and assistive technologies already understand these elements. ARIA adds extra accessibility information when native HTML alone cannot express what you need.

How ARIA complements HTML

Use ARIA when you need to:

  • Expose state
  • aria-expanded="true" on a collapsible button
  • aria-selected="true" in a tab or listbox
  • aria-checked="true" for custom checkable UI

  • Provide relationships

  • aria-labelledby to point to the visible label
  • aria-describedby to connect help text or error text
  • aria-controls to reference the element being affected

  • Define roles for custom widgets

  • If you build a custom tab UI, you may need roles like tablist, tab, and tabpanel
  • For custom dialogs, role="dialog" plus labeling attributes

  • Communicate live updates

  • aria-live="polite" for status messages that appear dynamically

Why native HTML should come first

Native elements usually give you:

  • semantics
  • keyboard behavior
  • focus handling
  • expected screen reader support

Example:

  • A real <button> already supports keyboard activation and is announced correctly.
  • A <div role="button"> requires you to manually add keyboard support, focusability, and behavior.

So the interview-friendly rule is:

  • Use native HTML whenever possible
  • Use ARIA only when native HTML cannot express the meaning or behavior

When to avoid ARIA

Avoid ARIA in these cases:

1. When a native element already does the job

Bad: - <div role="button">Submit</div>

Better: - <button>Submit</button>

Bad: - <div role="navigation">...</div>

Better: - <nav>...</nav>

2. When it duplicates or conflicts with native semantics

Example: - Adding role="button" to a <button> is unnecessary - Adding role="heading" to an actual <h2> is redundant

Worse, conflicting ARIA can make accessibility less reliable.

3. When it makes things less accessible

A custom control with ARIA but missing keyboard support is a common mistake.

Example: - A div with role="checkbox" but no Space key handling is not actually usable.

ARIA can describe a widget, but it does not give you behavior for free.

4. When using aria-hidden on meaningful content

If content should be available to screen readers, do not hide it with aria-hidden="true".

Also be careful not to put aria-hidden="true" on focusable elements or parents of focusable elements.

5. When using ARIA to fix visual-only problems

ARIA is for accessibility semantics, not styling or layout. It should not be used as a substitute for proper structure.

A strong interview line

A clean way to say it:

  • "ARIA enhances accessibility when native HTML is not enough, especially for custom widgets, dynamic state, and relationships between elements. But if a native element exists, I use that first, because ARIA cannot fully replace built-in semantics and behavior."

Common principle interviewers like

There is a well-known accessibility rule:

  • No ARIA is better than bad ARIA

That shows you understand that ARIA can help, but only when used correctly.

Practical examples

Good use of ARIA

  • Accordion button with aria-expanded
  • Input tied to error text with aria-describedby
  • Modal with role="dialog" and aria-labelledby
  • Live status message with aria-live

Bad use of ARIA

  • div pretending to be a button when <button> would work
  • Redundant roles on semantic elements
  • Adding ARIA labels that override clear visible text incorrectly
  • Using ARIA without keyboard and focus management

If you want a polished interview answer

You could say:

“ARIA complements native HTML by adding accessibility metadata for things HTML alone cannot fully express, like dynamic states, element relationships, live regions, and custom widgets. But I avoid ARIA when native semantic elements already provide the meaning and behavior, because built-in HTML is more reliable and requires less manual accessibility work. My rule is native first, ARIA only when needed.”

36. What is the difference between the script, async, and defer loading approaches in an HTML document, and how do they affect page rendering?

The main difference is when the browser downloads the script, when it executes it, and whether HTML parsing is blocked.

1. Plain <script>

Example: <script src="app.js"></script>

  • Browser starts parsing HTML.
  • When it hits the script tag, it stops parsing.
  • It downloads the script, if not already cached.
  • Then it executes the script immediately.
  • After that, HTML parsing continues.

Effect on rendering: - This can block page rendering and slow down initial load. - If the script is in the <head>, users may wait longer before seeing content.

Use it when: - The script must run right away at that exact point in the document. - The script depends on earlier HTML only, or intentionally blocks parsing.

2. <script async>

Example: <script src="analytics.js" async></script>

  • Browser parses HTML and downloads the script in parallel.
  • As soon as the script finishes downloading, it executes immediately.
  • HTML parsing pauses during execution, then resumes.

Effect on rendering: - Better than plain script for download performance. - But execution timing is unpredictable. - It can still interrupt parsing, so rendering may still be delayed briefly.

Use it when: - The script is independent. - It does not rely on other scripts. - Other scripts do not rely on it. - Good for analytics, ads, tracking, third-party widgets.

Key point: - Multiple async scripts do not guarantee execution order.

3. <script defer>

Example: <script src="main.js" defer></script>

  • Browser parses HTML and downloads the script in parallel.
  • It does not execute the script immediately when downloaded.
  • It waits until HTML parsing is finished.
  • Then deferred scripts execute in document order.

Effect on rendering: - This avoids blocking HTML parsing. - Usually the best choice for page scripts that need the DOM. - Rendering is generally smoother and faster.

Use it when: - The script needs the full DOM. - Script order matters. - You want non-blocking loading for regular app logic.

Key point: - Multiple defer scripts keep their order. - They run before DOMContentLoaded.

Quick comparison

  • Plain script
  • Download: when encountered
  • Execute: immediately when encountered
  • Blocks parsing: yes

  • async

  • Download: in parallel
  • Execute: as soon as ready
  • Blocks parsing: during execution
  • Order guaranteed: no

  • defer

  • Download: in parallel
  • Execute: after HTML parsing completes
  • Blocks parsing: no
  • Order guaranteed: yes

Simple rule of thumb

  • Use defer for most site JavaScript.
  • Use async for independent third-party scripts.
  • Use plain script only when you truly need immediate execution.

One interview-friendly way to say it

"script blocks parsing and runs right away, async downloads in parallel and runs as soon as it is ready, and defer downloads in parallel but waits until parsing is finished, which makes defer the safest default for most application code."

37. Tell me about a time you had to refactor poorly structured HTML in an existing project. What issues did you find, and how did you improve it?

A good way to answer this is:

  1. Start with the context, what the page or project was.
  2. Call out 2 to 4 specific HTML problems.
  3. Explain what you changed and why.
  4. End with the result, cleaner code, accessibility, maintainability, performance, or SEO improvements.

A strong answer sounds like this:

In one project, I inherited a marketing site that had grown quickly over time, so the HTML was pretty messy. It was built mostly by copying sections from older pages, and the structure had become inconsistent.

A few issues stood out right away:

  • Layout was built with too many generic div elements, with almost no semantic tags
  • Heading levels were out of order, like jumping from h1 to h4
  • There were repeated IDs across components
  • Some interactive elements were coded as styled div or span tags instead of proper button or a elements
  • Images were missing meaningful alt text, and form fields were missing proper labels

What I did first was audit the page structure section by section. I mapped out the content hierarchy and identified which parts were really navigation, hero content, feature sections, forms, and footer content.

Then I refactored the markup to make it more semantic:

  • Replaced generic wrappers with tags like header, nav, main, section, article, and footer where appropriate
  • Fixed heading order so the document had a logical outline
  • Replaced fake clickable elements with real button and a elements
  • Removed duplicated IDs and used classes or unique identifiers where needed
  • Added proper label associations for forms and improved image alt text
  • Simplified deeply nested markup so components were easier to read and maintain

I was careful not to break styling, so I worked incrementally and coordinated with CSS changes as needed. I also tested with browser dev tools and a screen reader to make sure the refactor actually improved accessibility.

The result was that the HTML became much easier for the team to maintain, accessibility issues dropped significantly, and it also made future CSS and JavaScript changes cleaner because the structure was more predictable.

If you want, I can also turn this into a more natural 30 second interview response.

38. If a form on your page is difficult to use with a keyboard or screen reader, how would you diagnose and fix the HTML-related problems?

I’d handle it in two parts, diagnose first, then fix the markup.

  1. Diagnose the problem

I’d test like a real keyboard and screen reader user first.

  • Keyboard only
  • Use Tab, Shift + Tab, Enter, Space, and arrow keys.
  • Check if every field, button, checkbox, radio, and link is reachable.
  • Make sure focus order is logical.
  • Make sure visible focus is obvious.
  • Check that I can submit and correct errors without a mouse.

  • Screen reader smoke test

  • Use something like NVDA or VoiceOver.
  • Move through the form field by field.
  • Listen for:

    • field label
    • input type
    • required state
    • help text
    • error text
    • group context for radios and checkboxes
  • Inspect the HTML

  • Verify every form control has a proper accessible name.
  • Check whether labels are real <label> elements, not just placeholder text.
  • See whether grouped controls use <fieldset> and <legend>.
  • Look for missing type, name, id, for, required, aria-describedby, aria-invalid.
  • Check for custom controls built from <div> or <span> instead of native elements.

  • Use browser/dev tools and audits

  • Accessibility tree in dev tools
  • Lighthouse or axe
  • These help catch missing labels, bad ARIA, and focus issues

  • Common HTML problems and how I’d fix them

Missing labels

  • Problem:
  • Inputs have no label, or rely only on placeholder text.
  • Fix:
  • Add a real <label for="email">Email</label> tied to <input id="email">.

Why: - Screen readers need a persistent accessible name. - Placeholders disappear and are not a replacement for labels.

Unclear grouping for radios or checkboxes

  • Problem:
  • A set of related options has no shared context.
  • Fix:
  • Wrap them in <fieldset> with a <legend>.

Example: - Payment method radio buttons should sit inside a fieldset with legend like Payment method.

Missing instructions or error association

  • Problem:
  • Help text or error text is visually present but not programmatically tied to the field.
  • Fix:
  • Use aria-describedby to connect the input to hint or error text.
  • Use aria-invalid="true" when validation fails.

Example: - An input can reference hint and error IDs, so screen readers announce both.

Using placeholders as labels

  • Problem:
  • Placeholder says “Phone number”, but there’s no label.
  • Fix:
  • Keep the placeholder only as an example format if needed, and add a visible label.

Custom controls instead of native HTML

  • Problem:
  • Clickable <div> pretending to be a checkbox, dropdown, or button.
  • Fix:
  • Replace with native <button>, <input type="checkbox">, <select>, etc.

Why: - Native controls come with keyboard support, semantics, and screen reader behavior for free.

Broken tab order

  • Problem:
  • Positive tabindex values or DOM order that doesn’t match visual flow.
  • Fix:
  • Remove custom tabindex where possible.
  • Keep elements in a logical DOM order.
  • Use native interactive elements.

Missing button type

  • Problem:
  • Buttons inside forms accidentally submit when they should not.
  • Fix:
  • Use type="button" for non-submit actions.
  • Use type="submit" for the actual submit action.

Required fields not exposed properly

  • Problem:
  • Required is shown visually with an asterisk only.
  • Fix:
  • Use the native required attribute.
  • Keep visible text too, so all users understand it.

Error handling not announced

  • Problem:
  • Form validation errors appear visually, but screen reader users do not know.
  • Fix:
  • Put error text near the field.
  • Associate it with aria-describedby.
  • Mark invalid fields with aria-invalid="true".
  • If there is an error summary, ensure focus moves to it or it is announced appropriately.

  • My practical workflow

If I were answering this in an interview, I’d say my process is:

  • Reproduce the issue with keyboard only
  • Test with a screen reader
  • Inspect accessible names, labels, grouping, and focus order
  • Prefer native HTML first
  • Add ARIA only where native HTML is not enough
  • Retest after each fix

  • Example answer you could give

“I’d start by testing the form using only the keyboard to check focus order, keyboard access, and visible focus. Then I’d run a quick screen reader test with NVDA or VoiceOver to hear how each field is announced. From there, I’d inspect the HTML for common issues like missing <label> elements, placeholders being used as labels, missing <fieldset> and <legend> for grouped inputs, and custom controls built with non-semantic elements.

To fix it, I’d use native form elements wherever possible, explicitly associate labels with inputs using for and id, connect help and error text with aria-describedby, and mark invalid fields with aria-invalid. I’d also make sure required fields use the native required attribute and that the tab order follows the DOM logically. After changes, I’d retest with keyboard and screen reader to confirm the form is actually usable.”

39. Describe your experience building responsive HTML layouts that work across multiple browsers and devices. What challenges have you faced?

A strong way to answer this is:

  1. Start with your scope, what kinds of pages or products you built.
  2. Mention your responsive approach, mobile-first, semantic HTML, flexible layouts.
  3. Call out browser and device testing.
  4. Finish with real challenges and how you solved them.

Example answer:

I’ve built responsive HTML layouts for landing pages, marketing sites, dashboards, and form-heavy web apps. My usual approach is mobile-first, starting with clean semantic HTML and then layering in responsive CSS using flexbox, grid, relative units, and media queries.

I focus on making layouts adapt naturally instead of just forcing them into a few screen sizes. That means things like fluid containers, flexible images, readable typography, and components that can stack, resize, or reflow depending on available space.

For cross-browser support, I test across Chrome, Safari, Firefox, and Edge, and I pay extra attention to mobile browsers, especially iOS Safari because it tends to expose layout quirks quickly. I also use browser dev tools for device simulation, but I try to validate on real devices whenever possible because touch behavior, viewport sizing, and font rendering can differ.

Some common challenges I’ve faced:

  • Inconsistent flexbox and grid behavior across browsers, especially with older Safari versions.
  • Viewport height issues on mobile, like 100vh not behaving consistently when browser UI appears or disappears.
  • Form controls rendering differently across browsers and operating systems.
  • Long text, tables, or card content breaking layouts on smaller screens.
  • Image scaling and maintaining aspect ratios without causing layout shifts.

How I’ve handled those:

  • I build with progressive enhancement in mind, so the core layout works even if a newer CSS feature behaves differently.
  • I use feature-safe patterns and test edge cases early, not just after the page looks done.
  • For mobile viewport issues, I avoid relying blindly on 100vh and use safer layout strategies depending on the screen and component.
  • I normalize spacing, box sizing, and typography early so the UI behaves more predictably.
  • I pay attention to accessibility as part of responsiveness, things like touch target size, zoom behavior, heading structure, and keyboard navigation.

One example was a dashboard where a multi-column desktop layout had to collapse cleanly to tablet and mobile without hurting usability. The challenge was that some widgets had dense data tables and fixed-width content. I restructured the HTML to keep a logical reading order, used flexible grid areas, and allowed lower-priority content to wrap or move below primary actions on smaller screens. That made the experience feel designed for each screen size instead of just shrunk down.

If this were in an interview, I’d keep it practical and emphasize that responsive HTML is not just about screen width, it’s about content structure, usability, and predictable behavior across real browsers and devices.

40. Imagine a stakeholder asks you to build a marketing page very quickly, but you are concerned about maintainability and accessibility. How would you balance speed, clean HTML structure, and long-term quality?

I’d answer this in two parts, how I’d approach it, and then what I’d actually do.

  1. Structure the answer
  2. Start with the tradeoff, acknowledge the need for speed.
  3. Show that speed does not mean sloppy foundations.
  4. Explain what you would simplify, and what you would not compromise on.
  5. End with how you’d communicate scope and follow-up work.

  6. How I’d handle it

I’d optimize for a fast first version, but I would protect the parts that are expensive to fix later.

What I’d move fast on: - Visual polish that can be iterated later - Fancy animations - Over-engineering components - Edge-case enhancements that are not critical for launch

What I would not cut: - Semantic HTML structure - Basic accessibility - Clear content hierarchy - Reusable, readable markup - Mobile responsiveness - Performance basics, like optimized images and avoiding unnecessary markup

My mindset is, clean HTML is not a luxury. It is usually the fastest way to build anyway, because messy structure slows you down the moment someone asks for revision two.

What I’d build first: - A solid page outline using semantic elements like header, main, section, nav, and footer - Proper heading order, so the content has a clear hierarchy - Accessible buttons, links, forms, and alt text where needed - Simple, consistent class naming, so future edits are easy - A layout that works on mobile first, then scales up

How I’d balance speed and quality in practice: - Use an existing design system or proven patterns if available - Reuse components instead of inventing one-off markup - Keep the HTML shallow and readable - Avoid div soup - Build the MVP version first, then add enhancements in a second pass - Document quick shortcuts I took, so the team knows what to revisit

I’d also be transparent with the stakeholder. Something like:

  • “I can get this live quickly if we focus on core sections first.”
  • “I’ll make sure the structure is semantic and accessible from the start.”
  • “If we need to cut anything for time, I’d cut nonessential effects, not the foundation.”
  • “After launch, I’d schedule a short cleanup pass for refinements.”

Concrete example:

If they wanted a landing page by end of day, I would: - Build the hero, benefits, social proof, and CTA sections first - Use semantic sections and correct headings immediately - Make sure contrast, keyboard access, and link/button labeling are correct - Use compressed images and responsive layout - Skip complex carousel behavior or heavy animation unless it was truly critical - Leave notes for post-launch improvements like animation polish or deeper CMS integration

That shows I can ship fast, but I’m still protecting maintainability and accessibility. In my experience, that is the best balance, because it delivers now without creating avoidable cleanup later.

Get Interview Coaching from HTML Experts

Knowing the questions is just the start. Work with experienced professionals who can help you perfect your answers, improve your presentation, and boost your confidence.

Complete your HTML interview preparation

Comprehensive support to help you succeed at every stage of your interview journey

Still not convinced? Don't just take our word for it

We've already delivered 1-on-1 mentorship to thousands of students, professionals, managers and executives. Even better, they've left an average rating of 4.9 out of 5 for our mentors.

Find HTML Interview Coaches