Interview Questions

Home Interview Questions

CAREER PREPARATION

HTML and CSS Interview Questions and Answers: Basic to Advanced

HTML and CSS Interview Questions and Answers: Basic to Advanced

Quick Answer

HTML and CSS interview questions evaluate a candidate's understanding of website structure, styling, layouts, responsive design, accessibility, and browser rendering. Freshers should prepare HTML elements, forms, semantic tags, CSS selectors, the box model, positioning, Flexbox, Grid, media queries, and practical coding problems. Advanced candidates should also understand specificity, stacking contexts, responsive units, animations, and modern CSS features.

Introduction

HTML and CSS are the foundation of modern web development. HTML defines the structure and meaning of webpage content, while CSS controls its appearance, layout, spacing, and visual presentation. Together, they help developers create websites that are accessible, responsive, and visually consistent across different devices.

During technical interviews, recruiters often begin with fundamental questions and gradually move towards practical coding challenges. Candidates may be asked to explain HTML elements, compare block-level and inline elements, identify differences between classes and IDs, or create responsive layouts using CSS.

Preparing with a structured collection of HTML and CSS Interview Questions and Answers helps candidates understand not only what each concept means but also how to apply it in real development situations.

This guide covers essential questions for beginners, freshers, and candidates preparing for more advanced front-end development interviews.

Section 1: HTML Interview Questions for Freshers

1. What is HTML?

HTML stands for HyperText Markup Language. It is the standard markup language used to structure content on web pages. HTML uses elements and tags to define headings, paragraphs, images, links, tables, forms, and other webpage components.

2. What is the difference between HTML and HTML5?

HTML5 is the modern version of HTML that introduced several improvements, including semantic elements, native audio and video support, and additional form input types.

HTML HTML5
Older versions had limited semantic elements. Provides semantic elements such as <header>, <nav>, and <article>.
External plugins were commonly used for multimedia. Supports native <audio> and <video> elements.
Had fewer built-in form input types. Introduced input types such as email, date, and number.
Had limited support for modern web application features. Includes APIs such as Canvas and Web Storage.

3. What are HTML tags and elements?

An HTML tag is the markup used to identify an element, while an HTML element generally consists of an opening tag, its content, and a closing tag.

Example:

<p>Welcome to web development.</p>

Here, <p> is the opening tag, </p> is the closing tag, and the complete structure is a paragraph element.

4. What is the purpose of the DOCTYPE declaration?

The <!DOCTYPE html> declaration tells the browser that the document uses HTML5. It helps the browser render the webpage in standards mode instead of quirks mode.

<!DOCTYPE html>
<html lang="en">
<head>
    <title>My Website</title>
</head>
<body>
    <h1>Hello World</h1>
</body>
</html>

5. What are semantic HTML elements?

Semantic elements clearly describe the meaning and purpose of their content. They improve document structure, accessibility, and maintainability.

Common semantic elements include:

  • <header> defines introductory content or a page header.
  • <nav> represents a section containing navigation links.
  • <main> identifies the primary content of a document.
  • <article> represents independent, self-contained content.
  • <section> groups related content.
  • <footer> defines footer information.

6. What is the difference between block-level and inline elements?

Block-level elements generally begin on a new line and occupy the available width of their containing block. Inline elements flow within the surrounding text and occupy only the space their content requires.

Examples:

Block-level elements Inline elements
<div> <span>
<p> <a>
<h1> <strong>
<section> <em>

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

The <div> element is a generic block-level container, while <span> is a generic inline container. Both are commonly used to group content for styling or scripting.

<div class="card">
    <h2>Web Development</h2>
    <p>Learn <span class="highlight">HTML and CSS</span>.</p>
</div>

8. What are HTML attributes?

Attributes provide additional information about HTML elements. They are usually written inside the opening tag as name-value pairs.

<a href="https://example.com" target="_blank">
    Visit Website
</a>

Here, href specifies the destination URL and target determines where the linked document opens.

9. What is the difference between an ID and a class in HTML?

An ID identifies a particular element and should be unique within the document. A class can be assigned to multiple elements to apply shared styling or behavior.

<h1 id="page-title">Welcome</h1>

<p class="description">First paragraph.</p>
<p class="description">Second paragraph.</p>

10. How do you insert an image in HTML?

The <img> element displays an image on a webpage. The src attribute specifies the image location, while alt provides alternative text.

<img src="images/profile.jpg"
     alt="Developer profile picture"
     width="300">

Alternative text is important for accessibility and helps communicate image meaning when the image cannot be displayed.

11. What is the difference between absolute and relative URLs?

An absolute URL contains the complete web address, including the protocol and domain. A relative URL identifies a resource based on the current document's location.

<!-- Absolute URL -->
<a href="https://example.com/about">About Us</a>

<!-- Relative URL -->
<a href="/about">About Us</a>

12. What are HTML forms?

HTML forms collect information from users through input fields, buttons, dropdowns, checkboxes, and other controls.

<form action="/register" method="post">
    <label for="name">Name:</label>
    <input type="text" id="name" name="name" required>

    <label for="email">Email:</label>
    <input type="email" id="email" name="email" required>

    <button type="submit">Register</button>
</form>

The action attribute specifies where the form data is sent, and method specifies the HTTP method used for submission.

13. What is the difference between GET and POST methods?

GET and POST are HTTP methods commonly used when submitting HTML forms.

GET POST
Sends data through the URL query string. Sends data in the request body.
Suitable for retrieving resources. Commonly used for submitting or changing data.
Parameters may appear in browser history. Submitted values do not normally appear in the URL.
Can be bookmarked with its query string. A form submission is not normally bookmarked as a URL.

POST does not automatically encrypt data. HTTPS is required to protect information during transmission.

14. What is the purpose of the alt attribute?

The alt attribute provides alternative text for an image. Screen readers use it to communicate meaningful image content to users, and browsers may display it if an image fails to load.

<img src="team.jpg" alt="Development team working together">

Decorative images can use an empty alt attribute so assistive technologies can ignore them.

15. What is the difference between <strong> and <b>?

The <strong> element indicates that its content has strong importance, seriousness, or urgency. The <b> element draws attention to text without adding the same semantic importance.

16. What is the difference between <em> and <i>?

The <em> element represents emphasized text, which can affect how assistive technologies interpret the content. The <i> element represents text set apart from normal prose, such as a technical term or foreign phrase.

17. What are HTML entities?

HTML entities represent reserved characters or symbols that may otherwise be interpreted as markup.

Examples:

Entity Output
&lt; <
&gt; >
&amp; &
&nbsp; Non-breaking space
&copy; ©

18. How do you create a hyperlink in HTML?

The <a> element creates hyperlinks that connect users to other pages, files, email addresses, or sections of a document.

<a href="https://example.com">Visit Example</a>

19. What is the purpose of the <meta> tag?

The <meta> tag provides metadata about an HTML document. It is commonly used to define character encoding, viewport behavior, and page descriptions.

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="Learn web development fundamentals.">
    <title>Web Development Guide</title>
</head>

20. What is the difference between local storage and session storage?

Both are browser Web Storage mechanisms that store data as key-value pairs.

Local Storage Session Storage
Data generally remains after the browser is closed. Data is generally cleared when the tab or browsing session ends.
Data is associated with the origin. Data is associated with the origin and a particular tab session.
Useful for persistent browser preferences. Useful for temporary session-specific information.

Neither should be used to store sensitive information without an appropriate security design.

21. What is the purpose of the <iframe> element?

The <iframe> element embeds another HTML page or document within the current webpage.

<iframe
    src="https://example.com"
    title="Embedded example page"
    width="600"
    height="400">
</iframe>

For security, embedded content should be trusted, and appropriate sandboxing and permissions should be considered.

22. What is the difference between <ol>, <ul>, and <dl>?

  • <ol> creates an ordered list in which items follow a sequence.
  • <ul> creates an unordered list in which items are generally displayed with bullets.
  • <dl> creates a description list containing terms and their descriptions.

23. What are HTML data attributes?

Custom data attributes allow developers to store additional information on HTML elements using names that begin with data-.

<button data-product-id="105">View Product</button>

JavaScript can access the value through the element's dataset property.

24. What is the difference between async and defer in JavaScript?

Both attributes allow external JavaScript files to be downloaded without blocking HTML parsing during the download.

  • async executes the script as soon as it is downloaded, so execution order is not guaranteed.
  • defer executes the script after HTML parsing is complete and preserves the order of deferred scripts.
<script src="analytics.js" async></script>
<script src="app.js" defer></script>

25. What is HTML accessibility?

HTML accessibility means creating webpages that can be used by people with different abilities, including users who rely on keyboards or screen readers.

Developers can improve accessibility by using semantic HTML, descriptive labels, meaningful alternative text, logical heading structures, and keyboard-friendly controls.

Section 2: CSS Interview Questions for Freshers

26. What is CSS?

CSS stands for Cascading Style Sheets. It is used to control the presentation of HTML documents, including colours, fonts, spacing, borders, layouts, and responsive behavior.

h1 {
    color: #2563eb;
    font-size: 32px;
    text-align: center;
}

27. What are the different types of CSS?

There are three common ways to apply CSS to HTML documents.

Inline CSS: Styles are written directly inside an HTML element.

<p style="color: blue;">Welcome</p>

Internal CSS: Styles are written inside a <style> element in the document's <head>.

<style>
    p {
        color: blue;
    }
</style>

External CSS: Styles are stored in a separate stylesheet and connected using a <link> element.

<link rel="stylesheet" href="style.css">

External CSS is generally preferred for maintainability and reuse across multiple pages.

28. What is a CSS selector?

A CSS selector identifies the HTML elements to which a set of styles should apply.

/* Element selector */
p {
    color: black;
}

/* Class selector */
.card {
    padding: 20px;
}

/* ID selector */
#header {
    background-color: navy;
}

29. What is the difference between class and ID selectors in CSS?

A class selector begins with a period (.) and can target multiple elements. An ID selector begins with a hash (#) and targets an element with a particular ID.

.highlight {
    color: green;
}

#main-heading {
    font-size: 30px;
}

30. What is the CSS box model?

The CSS box model explains how the dimensions of an element are calculated. It consists of four main areas: content, padding, border, and margin.

  • Content is the actual text or other material inside the element.
  • Padding is the space between the content and border.
  • Border surrounds the padding and content.
  • Margin creates space outside the border.
.card {
    width: 300px;
    padding: 20px;
    border: 2px solid black;
    margin: 15px;
}

With the default content-box sizing, the total width is 344px, excluding margins.

31. What is the difference between margin and padding?

Margin creates space outside an element's border, while padding creates space between the content and the border.

.box {
    margin: 20px;
    padding: 15px;
}

32. What is the difference between display: none and visibility: hidden?

Both properties make an element invisible, but they behave differently.

display: none visibility: hidden
Removes the element from the layout. Keeps the element's layout space.
The element is not displayed. The element is invisible but still occupies space.
Changes the layout of surrounding elements. Usually preserves the surrounding layout.

33. What are the different CSS positioning properties?

CSS provides five commonly used positioning values.

  • static follows the normal document flow.
  • relative positions an element relative to its normal position.
  • absolute positions an element relative to its nearest positioned ancestor.
  • fixed positions an element relative to the viewport.
  • sticky behaves like a relatively positioned element until its scroll threshold is reached.
.parent {
    position: relative;
}

.child {
    position: absolute;
    top: 10px;
    right: 10px;
}

34. What is the difference between relative and absolute positioning?

Relative positioning moves an element from its normal position while preserving its original layout space. Absolute positioning removes the element from normal document flow and positions it relative to its nearest positioned ancestor.

35. What is the z-index property?

The z-index property controls the stacking order of positioned elements and certain other elements within stacking contexts. An element with a higher applicable stack level generally appears above one with a lower level.

.modal {
    position: fixed;
    z-index: 1000;
}

A child element cannot escape its parent's stacking context simply by having a very large z-index.

36. What is the difference between px, em, and rem?

These are CSS units used to define dimensions and typography.

Unit Meaning
px CSS pixel, an absolute-length unit.
em Relative to the computed font size of the element, with inheritance affecting how it is resolved.
rem Relative to the root element's font size.
html {
    font-size: 16px;
}

h1 {
    font-size: 2rem;
}

p {
    font-size: 1em;
}

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

Display value Behaviour
block Starts on a new line and generally occupies the available width.
inline Flows within a line and does not accept width and height in the same way as block-level boxes.
inline-block Flows inline while allowing width and height to be set.

38. What is a pseudo-class in CSS?

A pseudo-class selects an element based on its state or position in a document.

button:hover {
    background-color: blue;
}

input:focus {
    border-color: green;
}

li:first-child {
    font-weight: bold;
}

39. What is a pseudo-element in CSS?

A pseudo-element allows developers to style a specific part of an element or insert generated content.

p::first-letter {
    font-size: 30px;
}

h2::after {
    content: " →";
}

Common pseudo-elements include ::before, ::after, ::first-line, and ::first-letter.

40. What is the difference between opacity: 0 and visibility: hidden?

opacity: 0 makes an element fully transparent but does not automatically remove it from interaction or accessibility. visibility: hidden hides the element and generally prevents it from receiving pointer interaction, while preserving its layout space.

41. What is the overflow property?

The overflow property controls how content is handled when it exceeds an element's content box.

Common values include:

  • visible allows overflowing content to remain visible.
  • hidden clips overflowing content.
  • scroll provides scrolling mechanisms.
  • auto provides scrolling when necessary.
.content {
    width: 250px;
    height: 120px;
    overflow: auto;
}

42. What is the difference between min-width, max-width, and width?

width defines an element's preferred width, min-width establishes a lower limit, and max-width establishes an upper limit.

.container {
    width: 90%;
    min-width: 280px;
    max-width: 1200px;
}

This pattern is useful for creating layouts that adapt to different screen sizes.

43. What is the CSS float property?

The float property moves an element to the left or right of its containing block, allowing surrounding inline content to flow around it.

img {
    float: left;
    margin-right: 15px;
}

Modern page layouts are generally better built using Flexbox or Grid rather than float.

44. What is the purpose of the clear property?

The clear property controls whether an element can appear beside floated elements. It can prevent content from flowing alongside a preceding float.

.footer {
    clear: both;
}

45. What is the difference between visibility, opacity, and display?

These properties affect element visibility in different ways.

  • display: none removes the element from the layout.
  • visibility: hidden hides the element while preserving its layout space.
  • opacity: 0 makes the element transparent while retaining its layout space.

Developers should also consider keyboard interaction and accessibility when hiding content.

Section 3: Basic HTML and CSS Interview Questions

46. What is the difference between HTML, CSS, and JavaScript?

HTML, CSS, and JavaScript perform different roles in front-end development.

Technology Main responsibility
HTML Defines the structure and content of a webpage.
CSS Controls the visual appearance and layout.
JavaScript Adds logic, interactivity, and dynamic behaviour.

47. What is responsive web design?

Responsive web design is an approach that allows websites to adapt their layout and content to different screen sizes and devices.

It commonly uses flexible layouts, fluid images, CSS media queries, and responsive units.

48. What is a CSS media query?

A media query applies CSS rules based on conditions such as viewport width, orientation, or user preferences.

.container {
    width: 90%;
    margin: auto;
}

@media (max-width: 768px) {
    .container {
        width: 95%;
    }
}

This example adjusts the container width on smaller screens.

49. What is the difference between Flexbox and CSS Grid?

Flexbox is primarily designed for one-dimensional layouts, while CSS Grid is designed for two-dimensional layouts involving rows and columns.

Flexbox CSS Grid
Works primarily along one axis at a time. Manages rows and columns together.
Useful for navigation bars and aligned components. Useful for page layouts and complex content grids.
Uses properties such as justify-content and align-items. Uses properties such as grid-template-columns and grid-template-rows.

50. What is CSS Flexbox?

Flexbox is a CSS layout model that helps distribute and align items within a container.

.container {
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 20px;
}

It is commonly used for navigation menus, card alignment, and responsive component layouts.

51. What are the main properties of Flexbox?

Important Flexbox properties include:

Property Purpose
display: flex Creates a flex container.
flex-direction Defines the main axis direction.
justify-content Aligns items along the main axis.
align-items Aligns items along the cross axis.
flex-wrap Controls whether items wrap onto additional lines.
gap Defines spacing between flex items.
flex-grow Controls how an item grows when extra space is available.
flex-shrink Controls how an item shrinks when space is limited.

52. What is CSS Grid?

CSS Grid is a two-dimensional layout system that organizes content into rows and columns.

.grid-container {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 20px;
}

This example creates three equal-width columns with consistent spacing.

53. What is the box-sizing property?

The box-sizing property determines how an element's declared width and height are calculated.

The two main values are:

  • content-box includes only the content in the declared width and height.
  • border-box includes content, padding, and border in the declared dimensions.

A common reset is:

*,
*::before,
*::after {
    box-sizing: border-box;
}

This makes layout sizing easier to manage.

54. What is the difference between max-content, min-content, and fit-content?

These intrinsic sizing keywords help CSS calculate an element's dimensions based on its content.

  • max-content sizes content based on its maximum preferred width without soft wrapping where possible.
  • min-content sizes content based on its minimum intrinsic size.
  • fit-content sizes content within available space, subject to intrinsic sizing constraints.

55. What is the difference between justify-content and align-items?

In Flexbox, justify-content aligns items along the main axis, while align-items aligns items along the cross axis.

The actual direction depends on the flex-direction value.

.container {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

56. What is the purpose of the object-fit property?

The object-fit property controls how replaced elements such as images and videos fit within their specified dimensions.

.product-image {
    width: 250px;
    height: 200px;
    object-fit: cover;
}

Common values include fill, contain, cover, none, and scale-down.

57. What is the difference between background-size: cover and contain?

cover scales the background image to fill the entire container, potentially cropping some parts. contain scales the image so the complete image remains visible, potentially leaving empty space.

58. What are CSS transitions?

CSS transitions create smooth changes between property values when a transition is triggered.

.button {
    background-color: blue;
    transition: background-color 0.3s ease;
}

.button:hover {
    background-color: darkblue;
}

59. What are CSS animations?

CSS animations allow developers to create multi-step visual effects using @keyframes.

@keyframes slideIn {
    from {
        transform: translateX(-30px);
        opacity: 0;
    }

    to {
        transform: translateX(0);
        opacity: 1;
    }
}

.card {
    animation: slideIn 0.5s ease;
}

60. What is the difference between a transition and an animation?

A transition generally changes a property between two states when triggered. An animation can define multiple stages using keyframes and can run automatically or repeatedly.

Section 4: HTML and CSS Technical Interview Questions

61. What is CSS specificity?

CSS specificity is the mechanism browsers use to determine which selector takes priority when multiple declarations target the same element and property.

A simplified specificity order is:

  1. Inline styles.
  2. ID selectors.
  3. Class, attribute, and pseudo-class selectors.
  4. Type selectors and pseudo-elements.

The cascade also considers origin, importance, cascade layers, and source order. Therefore, specificity alone does not decide every conflict.

Example:

p {
    color: black;
}

.description {
    color: blue;
}

#intro {
    color: red;
}

If the same paragraph matches all three selectors under otherwise equal cascade conditions, the ID selector wins.

62. What is the !important rule in CSS?

The !important annotation gives a declaration priority within the relevant cascade origin and importance level. It can override normal declarations, but it should be used carefully because it makes styles harder to maintain.

p {
    color: red !important;
}

A better approach is usually to correct selector specificity or the cascade structure rather than relying heavily on !important.

63. What is the difference between descendant and child selectors?

A descendant selector selects matching elements at any depth inside another element. A child selector selects only direct children.

/* All paragraphs inside a section */
section p {
    color: blue;
}

/* Only direct child paragraphs */
section > p {
    color: green;
}

64. What is the difference between :nth-child() and :nth-of-type()?

:nth-child() selects an element based on its position among all siblings. :nth-of-type() selects an element based on its position among siblings of the same element type.

li:nth-child(2) {
    color: red;
}

p:nth-of-type(2) {
    color: blue;
}

65. What is the difference between min() and max() in CSS?

The min() function returns the smallest value from the supplied expressions, while max() returns the largest value.

.container {
    width: min(90%, 1200px);
}

.heading {
    font-size: max(24px, 3vw);
}

These functions help create flexible layouts without requiring many separate media queries.

66. What is the CSS clamp() function?

The clamp() function sets a value within a defined minimum and maximum range, using a preferred value between them.

h1 {
    font-size: clamp(28px, 5vw, 56px);
}

The heading scales with the viewport while remaining within the specified limits.

67. What are CSS custom properties?

CSS custom properties, commonly called CSS variables, allow developers to store reusable values.

:root {
    --primary-color: #2563eb;
    --spacing: 20px;
}

.button {
    background-color: var(--primary-color);
    padding: var(--spacing);
}

They make global design changes easier and support dynamic theming.

68. What is the difference between transform and position?

position controls how an element participates in document layout and where it is placed. transform visually modifies an element using operations such as translation, rotation, scaling, and skewing.

.card {
    transform: translateY(-10px);
}

A transform does not normally change the original space reserved by the element in the document flow.

69. What is a stacking context in CSS?

A stacking context is a self-contained layer hierarchy used by the browser to determine how elements overlap.

Stacking contexts can be created by properties such as positioned elements with a non-auto z-index, certain transforms, opacity values below 1, and some other CSS features.

Understanding stacking contexts helps resolve issues involving dropdowns, modals, and overlapping elements.

70. What is the difference between relative, absolute, and fixed positioning in a responsive layout?

Relative positioning preserves an element's normal layout space. Absolute positioning removes the element from normal flow and places it relative to a positioned ancestor. Fixed positioning places an element relative to the viewport, so it generally stays in the same viewport position while the page scrolls.

The best option depends on the layout requirement rather than the device alone.

71. What is lazy loading in HTML?

Lazy loading delays the loading of certain resources until they are closer to being needed. For images and iframes, HTML supports the loading="lazy" attribute.

<img src="gallery-image.jpg"
     alt="Modern office interior"
     loading="lazy">

This can reduce unnecessary initial loading, especially on pages with many below-the-fold images. Important above-the-fold or Largest Contentful Paint images should not be lazy-loaded without a good reason.

72. What is the difference between preload, prefetch, and preconnect?

These resource hints help browsers prepare for resources that may be needed.

  • preload requests a resource early because it is important for the current page.
  • prefetch suggests a resource that may be needed for a future navigation.
  • preconnect establishes an early connection to another origin.

They should be used selectively because unnecessary hints can compete for bandwidth and affect performance.

73. How can you improve website performance using HTML and CSS?

Website performance can be improved by reducing unnecessary resources, optimizing images, minimizing unused CSS, and choosing efficient layouts.

Useful techniques include:

  • Use semantic HTML to create a clear document structure.
  • Load only the CSS required by the page.
  • Compress and resize images appropriately.
  • Use modern image formats such as WebP or AVIF when supported by the delivery setup.
  • Apply responsive image techniques using srcset and sizes.
  • Avoid unnecessary animations and expensive visual effects.
  • Use font loading strategies that reduce layout shifts.
  • Lazy-load appropriate below-the-fold images and embedded content.
  • Minimize layout shifts by specifying image dimensions or aspect ratios.

74. What is the difference between src and srcset in an image element?

src specifies the default image source, while srcset provides multiple image candidates so the browser can select an appropriate resource based on the device and display conditions.

<img
    src="image-800.jpg"
    srcset="image-400.jpg 400w,
            image-800.jpg 800w,
            image-1200.jpg 1200w"
    sizes="(max-width: 600px) 100vw, 800px"
    alt="Responsive website preview">

This allows browsers to choose a suitable image rather than always downloading the same file.

75. What is the difference between @media and @supports in CSS?

@media applies CSS based on media conditions such as viewport width or user preferences. @supports applies styles when the browser supports a specified CSS feature.

@supports (display: grid) {
    .layout {
        display: grid;
    }
}

76. What is the purpose of prefers-reduced-motion?

The prefers-reduced-motion media feature detects whether a user has requested reduced motion through their operating system or browser settings.

@media (prefers-reduced-motion: reduce) {
    *,
    *::before,
    *::after {
        animation-duration: 0.01ms !important;
        transition-duration: 0.01ms !important;
    }
}

Developers should avoid unnecessary movement and preserve essential visual feedback.

77. What is the difference between vh, vw, svh, lvh, and dvh?

These are viewport-relative CSS units.

  • vh represents one percent of the viewport height.
  • vw represents one percent of the viewport width.
  • svh represents one percent of the small viewport height.
  • lvh represents one percent of the large viewport height.
  • dvh represents one percent of the dynamic viewport height.

The newer viewport units help developers handle changing browser interface sizes on mobile devices.

78. What is CSS containment?

CSS containment allows developers to limit how certain layout, style, and paint operations affect other parts of a page.

.widget {
    contain: layout paint;
}

Containment can improve rendering efficiency in suitable cases, but it may also change layout and painting behaviour. It should be applied only after testing.

79. What are CSS container queries?

Container queries allow styles to respond to the size or characteristics of a component's containing context rather than relying only on the viewport size.

.card-wrapper {
    container-type: inline-size;
}

@container (min-width: 500px) {
    .card {
        display: grid;
        grid-template-columns: 1fr 1fr;
    }
}

They are especially useful for reusable components that appear in different layout regions.

80. What is the difference between :is(), :where(), and :has()?

These are modern CSS selector functions.

  • :is() groups multiple selectors and takes the specificity of its most specific argument.
  • :where() groups selectors but always contributes zero specificity.
  • :has() selects an element based on whether it contains or is related to elements matching the supplied relative selector.
/* Group multiple heading selectors */
:is(h1, h2, h3) {
    font-family: Arial, sans-serif;
}

/* Style a card that contains an image */
.card:has(img) {
    border: 1px solid #ddd;
}

/* Group selectors without adding specificity */
:where(header, footer) a {
    text-decoration: none;
}

Section 5: Practical HTML and CSS Coding Interview Questions

Technical interviews frequently include small coding tasks to evaluate whether candidates can apply concepts rather than simply define them. The following examples cover common beginner and intermediate challenges.

81. How do you create a basic HTML webpage?

A basic HTML page contains a document declaration, an HTML root element, a head section, and a body section.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My First Webpage</title>
</head>
<body>
    <header>
        <h1>Welcome to My Website</h1>
    </header>

    <main>
        <p>This is my first HTML webpage.</p>
    </main>

    <footer>
        <p>Copyright 2026</p>
    </footer>
</body>
</html>

82. How do you create a navigation menu using HTML and CSS?

A navigation menu can be created using a semantic <nav> element with a list of links.

<nav class="navbar">
    <ul>
        <li><a href="/">Home</a></li>
        <li><a href="/about">About</a></li>
        <li><a href="/services">Services</a></li>
        <li><a href="/contact">Contact</a></li>
    </ul>
</nav>

.navbar ul {
    display: flex;
    gap: 25px;
    list-style: none;
    padding: 0;
}

.navbar a {
    text-decoration: none;
    color: #222;
}

83. How do you centre a div horizontally and vertically?

Flexbox provides a straightforward way to centre an element along both axes.

.parent {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 100vh;
}

The child element is centred within the available parent area.

84. How do you create a two-column layout using CSS Grid?

CSS Grid can create a two-column layout with a defined proportion between the columns.

<div class="layout">
    <aside>Sidebar</aside>
    <main>Main Content</main>
</div>

.layout {
    display: grid;
    grid-template-columns: 1fr 3fr;
    gap: 20px;
}

85. How do you create a responsive card layout?

A responsive card layout can use CSS Grid's auto-fit and minmax() functions to adapt the number of columns based on available space.

<div class="cards">
    <article class="card">HTML</article>
    <article class="card">CSS</article>
    <article class="card">JavaScript</article>
</div>

.cards {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
    gap: 20px;
}

.card {
    padding: 24px;
    border: 1px solid #ddd;
    border-radius: 8px;
}

86. How do you create a button hover effect?

A hover effect can be created using the :hover pseudo-class and a CSS transition.

<button class="primary-btn">Get Started</button>

.primary-btn {
    background: #2563eb;
    color: white;
    padding: 12px 24px;
    border: none;
    border-radius: 6px;
    transition: background-color 0.3s ease;
}

.primary-btn:hover {
    background: #1d4ed8;
}

For keyboard users, also provide a visible :focus-visible style.

87. How do you create a responsive image?

An image can be made responsive by limiting its width to the available container width while maintaining its aspect ratio.

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

For more advanced responsive image delivery, developers can use srcset and sizes.

88. How do you create a simple login form using HTML and CSS?

A login form uses labels and input controls to collect credentials.

<form class="login-form">
    <h2>Login</h2>

    <label for="email">Email Address</label>
    <input type="email" id="email" required>

    <label for="password">Password</label>
    <input type="password" id="password" required>

    <button type="submit">Login</button>
</form>

.login-form {
    max-width: 350px;
    margin: 30px auto;
    padding: 24px;
    border: 1px solid #ddd;
    border-radius: 8px;
}

.login-form input {
    width: 100%;
    padding: 10px;
    margin: 8px 0 16px;
    box-sizing: border-box;
}

This example demonstrates the visual structure only. Real authentication requires server-side validation, secure password handling, and appropriate session management.

89. How do you create a CSS-only dropdown menu?

A simple dropdown can use a parent element with a nested menu that becomes visible on hover or keyboard focus.

<div class="dropdown">
    <button type="button">Services</button>

    <div class="dropdown-menu">
        <a href="/web-design">Web Design</a>
        <a href="/development">Development</a>
    </div>
</div>

.dropdown {
    position: relative;
    display: inline-block;
}

.dropdown-menu {
    display: none;
    position: absolute;
    top: 100%;
    left: 0;
    min-width: 160px;
    background: white;
    box-shadow: 0 4px 10px #0002;
}

.dropdown-menu a {
    display: block;
    padding: 10px;
}

.dropdown:hover .dropdown-menu,
.dropdown:focus-within .dropdown-menu {
    display: block;
}

For production interfaces, developers should also consider touch interaction, keyboard behaviour, focus management, and accessible menu semantics.

90. How do you create a sticky header?

A sticky header remains in the normal document flow until it reaches a specified scroll position.

.header {
    position: sticky;
    top: 0;
    z-index: 100;
    background: white;
}

The parent container and surrounding layout should be checked to ensure they do not prevent the expected sticky behaviour.

Section 6: Advanced HTML and CSS Interview Questions

91. What is the difference between CSS inheritance and the cascade?

Inheritance determines whether certain property values are passed from a parent element to its descendants. The cascade determines which declaration wins when multiple CSS rules apply to the same element and property.

For example, text colour is commonly inherited, while margin is not inherited by default.

92. What is a CSS reset or normalize stylesheet?

A CSS reset reduces browser default styling differences by removing or standardising default styles. A normalize stylesheet aims to make default styling more consistent while preserving useful browser defaults.

Both approaches help developers establish a predictable styling foundation.

93. What is critical CSS?

Critical CSS refers to the minimum CSS needed to render the initially visible portion of a webpage. Delivering it efficiently can help improve initial rendering performance, especially when combined with appropriate loading of the remaining stylesheet.

94. What is the difference between reflow and repaint?

Reflow, also called layout, occurs when the browser recalculates the size or position of elements. Repaint occurs when the browser redraws visual properties such as colours or borders without necessarily recalculating layout.

Frequent layout changes can affect performance, so developers should avoid unnecessary DOM and style updates.

95. What are web fonts, and how do you use them in CSS?

Web fonts allow developers to use typefaces beyond the fonts installed on a user's device. They can be loaded through a font provider or self-hosted font files.

@font-face {
    font-family: "CustomFont";
    src: url("/fonts/custom-font.woff2") format("woff2");
    font-display: swap;
}

body {
    font-family: "CustomFont", Arial, sans-serif;
}

Using efficient font formats and limiting unnecessary font weights can improve performance.

96. What is the difference between CSS variables and Sass variables?

CSS custom properties are available at runtime in the browser and can participate in the cascade and inheritance. Sass variables are processed during compilation and are replaced with their values in the generated CSS.

:root {
    --theme-color: blue;
}

button {
    background: var(--theme-color);
}

$theme-color: blue;

button {
    background: $theme-color;
}

97. What is the purpose of will-change in CSS?

The will-change property allows developers to indicate that an element is likely to change a particular property, giving the browser an opportunity to prepare for the change.

.card:hover {
    will-change: transform;
}

It should be used sparingly because unnecessary use can consume memory and reduce performance.

98. What is the difference between transform: translate() and using top or left?

transform: translate() visually moves an element without changing its original layout position. Properties such as top and left affect the placement of positioned elements and may trigger layout work depending on the change.

Transforms are often suitable for animations because they can be handled efficiently by browsers.

99. What is the purpose of aspect-ratio in CSS?

The aspect-ratio property defines a preferred width-to-height ratio for an element.

.video-container {
    width: 100%;
    aspect-ratio: 16 / 9;
}

It helps maintain consistent image, video, and card proportions without manually calculating both dimensions.

100. What are logical properties in CSS?

Logical properties define dimensions and spacing based on writing direction and text flow rather than fixed physical directions.

.card {
    margin-inline: auto;
    padding-block: 20px;
    border-inline-start: 3px solid blue;
}

They help support languages and layouts that use different writing directions.

Section 7: Practical Preparation Strategy for HTML and CSS Interviews

Knowing definitions is important, but interviewers also want to see how candidates approach real development problems. A useful preparation method combines concept revision, hands-on coding, and explanation practice.

1. Build a Strong Foundation

Begin by understanding HTML document structure, semantic elements, attributes, forms, links, images, and accessibility. In CSS, focus on selectors, the box model, display values, positioning, typography, and spacing.

Candidates should be able to explain each concept using a small example rather than memorising textbook definitions.

2. Practise Responsive Layouts

Create a simple website containing a header, navigation menu, hero section, card grid, and footer. Make it work across mobile, tablet, and desktop screen sizes using Flexbox, Grid, and media queries.

3. Work on Real Coding Challenges

Practise building a login form, navigation bar, responsive gallery, product card, dropdown menu, and two-column layout. These tasks help demonstrate practical understanding during technical interviews.

4. Understand Browser Behaviour

Learn how browsers interpret HTML, apply CSS rules, calculate layout, and render visual content. Understanding specificity, inheritance, stacking contexts, and responsive units will help candidates answer more challenging questions.

5. Prepare to Explain Your Code

During an interview, explain why you selected a particular layout method, how your solution adapts to different screens, and what accessibility or performance considerations you included.

For structured practical preparation, candidates can strengthen their front-end development fundamentals through training and interview guidance at Well Spring Talent Solutions.

HTML and CSS Interview Preparation Checklist

Before attending an interview, candidates should be comfortable with the following topics.

  • Explain HTML structure, tags, elements, and attributes.
  • Understand semantic HTML and accessibility.
  • Create forms, tables, hyperlinks, and image elements.
  • Explain the differences between HTML, CSS, and JavaScript.
  • Understand CSS selectors, specificity, and inheritance.
  • Explain the CSS box model and positioning.
  • Build layouts using Flexbox and CSS Grid.
  • Create responsive webpages using media queries.
  • Understand pseudo-classes and pseudo-elements.
  • Work with transitions, animations, and custom properties.
  • Understand modern CSS features such as container queries and clamp().
  • Build and explain small practical webpage components.

Conclusion

HTML and CSS are essential skills for anyone entering front-end web development. A strong understanding of HTML structure, semantic elements, CSS styling, responsive layouts, and modern browser features helps candidates approach technical interviews with confidence.

Freshers should first master the fundamentals before moving towards advanced topics such as CSS Grid, Flexbox, specificity, container queries, and performance optimisation. Regular coding practice is equally important because interviewers often evaluate how candidates apply their knowledge to real-world interface requirements.

Use these HTML and CSS interview questions and answers as a structured revision resource, practise the examples independently, and prepare to explain your approach clearly. A combination of conceptual understanding and practical implementation will help you build a stronger foundation for front-end development opportunities.

Frequently Asked Questions (FAQs)

1. What are the most important HTML interview questions for freshers?

Freshers should prepare questions about HTML tags, elements, attributes, semantic HTML, forms, hyperlinks, images, tables, metadata, and the difference between HTML and HTML5. They should also practise writing a complete HTML document.

2. What are the most common CSS interview questions for freshers?

Common CSS interview topics include selectors, the box model, margin and padding, positioning, display properties, Flexbox, Grid, media queries, pseudo-classes, and responsive design.

3. How can I prepare for HTML and CSS technical interviews?

Start by revising fundamental concepts, then practise creating webpages and responsive components. Review common technical questions, understand browser behaviour, and explain your code in simple terms.

4. Is HTML and CSS enough to get a front-end developer job?

HTML and CSS provide the foundation for front-end development, but most front-end developer roles also require JavaScript. Knowledge of Git, responsive design, accessibility, browser developer tools, and a front-end framework may also be expected depending on the role.

5. What practical tasks are asked in HTML and CSS interviews?

Candidates may be asked to create navigation menus, login forms, responsive card layouts, image galleries, dropdown menus, landing page sections, and layouts using Flexbox or CSS Grid.

6. What is the difference between Flexbox and Grid in CSS?

Flexbox is mainly used to arrange items along a single dimension, either horizontally or vertically. CSS Grid is designed for layouts that need control over both rows and columns.

7. How long does it take to learn HTML and CSS for interviews?

The time required depends on prior experience and practice. A beginner who studies consistently and builds small projects can develop a solid foundation over several weeks, while more advanced interview preparation requires additional practice with responsive layouts, accessibility, performance, and modern CSS features.

Back to Interview Questions
YOUR CAREER STARTS HERE

Ready to Prepare for Your Software Developer Interview?

Strengthen your programming fundamentals, practise technical interview questions, and build confidence for your next software developer interview with guidance from Well Spring Talent Solutions.

Learn Today. Build Tomorrow. Succeed for Life.

Your Local Destination for IT Training

We provide IT training, internships, and online learning for students in Trichy and across India.

IT Training Areas in Trichy

Thillai Nagar KK Nagar Srirangam Cantonment Woraiyur Tennur Karumandapam Edamalaipatti Pudur Puthur Crawford BHEL Township Ariyamangalam Kattur Ponmalai (Golden Rock) Vayalur Road Bharathidasan Salai Chathiram Bus Stand Palakkarai Subramaniapuram Sangiliyandapuram Trichy Airport Area Thiruverumbur Samayapuram Manachanallur Panjappur Navalpattu Central Bus Stand Trichy Railway Junction Gandhi Market Palpannai Anna Nagar Thiruvanaikoil TVS Tollgate Ponnagar Beemanagar Kallukuzhi Thuvakudi Pudukottai Road Thanjavur Road Karur Bypass Road

Online IT Training Across India

Can't attend classes in person? Explore online IT training opportunities with Well Spring Talent Solutions, designed to help learners develop practical technology skills from different locations across India.

Join Our WhatsApp Channel 💬

Join our WhatsApp community for internship updates, IT courses, placement support, and latest job opportunities.

Join Now