HTML & CSS Interview Questions and Answers

Semantics, accessibility, layout systems, responsive design and modern CSS.

Practise 10 random 68 peer-reviewed questions
HTML & CSS Interview Syllabus & Preparation Strategy

Whether you are preparing for entry-level HTML & CSS interview questions for freshers or senior software engineer interview questions addressing concurrency, scalability, and system architecture, this track provides peer-reviewed model answers with syntax walkthroughs, edge cases, and practical interview tips.

1 Explain Flexbox vs Grid and when to use each. Medium
  • Flexbox is one-dimensional: it distributes space along a single main axis (row or column). Best for toolbars, navigation, card content, alignment, and components whose size depends on their content.
  • Grid is two-dimensional: it controls both rows and columns simultaneously. Best for page layouts, dashboards, galleries and any design with a defined track structure.

They compose: use Grid for the macro layout and Flexbox inside individual components.

.grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); gap: 1rem; }
.flex { display: flex; align-items: center; justify-content: space-between; }
2 How does CSS specificity work and how do you resolve conflicts? Medium

Specificity ranks selectors as (inline, IDs, classes/attributes/pseudo-classes, elements/pseudo-elements). Higher wins; equal specificity falls back to source order (later wins). !important overrides normal declarations regardless of specificity and should be reserved for utilities or third-party overrides.

#nav .item a:hover  -> (0, 1, 2, 2)
.item.active        -> (0, 0, 2, 0)

Strategies to avoid wars: keep specificity low and flat, use single-class selectors, adopt a naming convention (BEM), or use cascade layers (@layer) and :where() (zero specificity) to control the cascade deliberately.

3 What is the difference between relative, absolute, fixed and sticky positioning? Medium
  • static: default, follows normal flow.
  • relative: stays in flow but offsets from its normal position; also establishes a containing block for absolutely positioned descendants.
  • absolute: removed from flow, positioned relative to the nearest positioned ancestor (or the initial containing block).
  • fixed: removed from flow, positioned relative to the viewport and unaffected by scrolling.
  • sticky: behaves as relative until a threshold is crossed, then sticks within its scrolling ancestor; it needs a top/right/bottom/left value.

Common bug: an absolute child escapes to the viewport because no ancestor has position set. Add position: relative to the intended parent.

4 How do you make a site accessible and responsive? Medium

Accessibility essentials:

  • Use semantic elements and a logical heading order.
  • Provide alt text for meaningful images and empty alt for decorative ones.
  • Ensure colour contrast of at least 4.5:1 for body text.
  • Support full keyboard navigation with visible focus styles.
  • Associate labels with inputs and announce errors with aria-live.
  • Respect prefers-reduced-motion and prefers-color-scheme.

Responsive essentials:

  • Set the viewport meta tag.
  • Use fluid layouts (flex/grid), relative units (rem, %, clamp) and max-width.
  • Mobile-first media queries plus container queries for component-level responsiveness.
  • Serve responsive images with srcset/sizes and loading="lazy".
5 What are different types of list in HTML? Medium

HTML provides three primary elements for structuring lists of items, each serving a distinct semantic role:

### 1. Unordered Lists (<ul>)
Used for collections of items where the sequence does not convey procedural priority or hierarchy. Browsers render these with bullet points by default:

<ul>
  <li>Cascading Style Sheets (CSS)</li>
  <li>HyperText Markup Language (HTML)</li>
  <li>JavaScript (JS)</li>
</ul>

### 2. Ordered Lists (<ol>)
Used for step-by-step instructions, ranked leaderboards, or sequential procedures where order is essential:

<ol type="1" start="1">
  <li>Initialize Git repository</li>
  <li>Configure remote origin</li>
  <li>Commit and push changes</li>
</ol>

*Attributes:* type ("1", "a", "A", "i", "I"), start, and reversed.

### 3. Description / Definition Lists (<dl>)
Used to group pairs of terms (<dt>) and descriptions/values (<dd>), ideal for glossaries, metadata displays, or key-value pairings:

<dl>
  <dt>DOM</dt>
  <dd>Document Object Model — a tree representation of HTML nodes.</dd>
  <dt>API</dt>
  <dd>Application Programming Interface.</dd>
</dl>
6 What are the different types of input field in HTML? Medium

The HTML <input> element is one of the most versatile form controls, determined by its type attribute:

### Common Input Types and Behaviors:

  1. text: Standard single-line plain text entry.
  2. password: Obscures characters with dots/asterisks for credential security.
  3. email: Validates email format and displays @ symbol on mobile soft keyboards.
  4. number: Restricts entry to digits with optional min, max, and step attributes.
  5. tel: Mobile phone number entry triggering numeric telephone keypad.
  6. url: Enforces valid URL protocol prefixes (http:// or https://).
  7. checkbox: Toggle option for multiple selectable choices.
  8. radio: Mutually exclusive selection within a shared name group.
  9. file: File upload picker with accept and multiple attribute support.
  10. date, time, datetime-local: Native calendar and clock pickers.
  11. range: Visual slider control between numeric bounds.
  12. color: Native hex color picker dialog.
  13. hidden: Stores invisible state transmitted upon form submission.
  14. submit, reset, button: Action buttons trigger submission or reset events.
7 What are void elements in HTML? Medium

Void elements (historically called self-closing or empty elements) are HTML elements that cannot have any child nodes (neither text nor nested elements) and must never have a closing tag (</...>).

### Complete List of HTML5 Void Elements:

  • <area>: Image map active region
  • <base>: Base URL for relative paths
  • <br>: Line break
  • <col>: Column properties in a table
  • <embed>: External application or plugin container
  • <hr>: Thematic break (horizontal line)
  • <img>: Image element
  • <input>: Form control
  • <link>: Document relationship metadata (e.g. stylesheets)
  • <meta>: Document metadata
  • <param>: Plugin parameter
  • <source>: Media resource for <audio> and <video>
  • <track>: Text track for subtitles
  • <wbr>: Word break opportunity

### HTML5 Syntax Note:
In modern HTML5, writing <br> or <br /> is functionally identical; the trailing slash is purely optional and originates from strict XML/XHTML compatibility.

8 Can we display web page inside a webpage or is nesting of webpage possible? Medium

Yes, nesting a webpage inside another webpage is possible in HTML using the <iframe> (Inline Frame) element:

<iframe 
  src="https://example.com/embed" 
  width="800" 
  height="450" 
  title="Interactive Sandbox"
  loading="lazy"
  sandbox="allow-scripts allow-same-origin"
  referrerpolicy="no-referrer">
</iframe>

### Security Considerations & Clickjacking Defense:

  1. The sandbox Attribute: Highly recommended when embedding third-party content. It restricts execution of untrusted scripts, form submissions, and popups.
  2. X-Frame-Options & CSP frame-ancestors:

Websites can block themselves from being framed using HTTP response headers (X-Frame-Options: DENY or frame-ancestors 'none') to protect against Clickjacking attacks. If a destination site sends this header, modern browsers will refuse to display it inside an iframe.

9 What are some of the advantages of HTML5 over its previous versions? Medium

HTML5 revolutionized the web platform by deprecating proprietary plugins (like Flash and Silverlight) and standardizing modern web application capabilities:

### Major Advantages:

  1. Semantic Structure Elements: Introduced <header>, <footer>, <article>, <section>, and <nav> to replace generic <div> tags, vastly improving SEO and accessibility.
  2. Native Multimedia Support: Introduced <video> and <audio> tags for native media playback without external browser plugins.
  3. Interactive Graphics (<canvas> & SVG): Native 2D/3D hardware-accelerated rendering directly in the browser.
  4. Client-Side Storage: Replaced restrictive 4KB cookies with localStorage (5-10MB) and IndexedDB for offline Progressive Web Apps (PWAs).
  5. Modern Form Controls: Native validation attributes (required, pattern) and specialized input types (email, date, number).
  6. Web APIs Integration: Geolocation API, WebSockets, Web Workers (background threading), and Drag-and-Drop.
10 What would happen if there is no text between the HTML tags? Medium

There would be nothing to format if there is not text present between the tags. Therefore, nothing will appear on the screen. Tags without closing tag like <img> do not require any text between them.

11 How do you change the color of bullets? Medium

The color of the bullet is always the color of the first text of the list. So, if we can change the color of the bullets by changing the color of the text.

12 What will happen if we don't put <!DOCTYPE HTML> tag? Medium

If we don't put <!DOCTYPE html> tag, the browser will not be able to identify that it is an HTML document and HTML5 tags will not function properly.

13 How can you make an image clickable in HTML? Medium

To make an image clickable, we have to use anchor tag with the image tag nested inside it and specify where we want to be directed to in "href" attribute when image in click.

14 What are the different tags used in an HTML table? Medium

| Tag Name | Definition |
| ----------- | -------------------------------------------------------------- |
| <table> | Defines a table |
| <caption> | Defines a title or caption for a table |
| <thead> | Defines the header of a table |
| <tbody> | Defines the body of a table |
| <tfoot> | Defines the footer of a table |
| <tr> | Defines a row in a table |
| <th> | Defines a header cell in a table |
| <td> | Defines a standard cell in a table |
| <colgroup> | Defines a group of columns in a table |
| <col> | Specifies column properties for each column within <colgroup> |
| <caption> | Defines a title or caption for a table |

15 What are the key attributes used in HTML tables? Medium

| Attribute | Description |
| ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| border | Specifies the width of the border around the table. |
| cellpadding | Specifies the amount of padding to be added to the cells in the table. |
| cellspacing | Specifies the amount of space to be added between cells in the table. |
| width | Specifies the width of the table. |
| height | Specifies the height of the table. |
| align | Specifies the horizontal alignment of the table within its containing element. Possible values are left, center, right, and justify. |
| valign | Specifies the vertical alignment of the table within its containing element. Possible values are top, middle, bottom, and baseline. |
| bgcolor | Specifies the background color of the table. |
| bordercolor | Specifies the color of the border around the table. |
| border-collapse | Specifies whether the borders of the cells in the table should be collapsed into a single border or not. Possible values are collapse and separate. Default is separate. |
| border-spacing | Specifies the amount of space to be added between the cells in the table when the border-collapse property is set to separate. |
| caption | Specifies the title or caption of the table. |
| caption-side | Specifies the side of the table on which to place the caption. Possible values are top, bottom, left, and right. Default is top. |
| empty-cells | Specifies whether or not to display borders around empty cells in the table. Possible values are show and hide. Default is show. |
| frame | Specifies which sides of the table should have borders. Possible values are void, above, below, hsides, vsides, lhs, rhs, and box. |
| rules | Specifies which parts of the table's border should be shown. Possible values are none, groups, rows, cols, and all. Default is none. |
| summary | Specifies a summary of the contents of the table. |
| dir | Specifies the direction of the table's text. Possible values are ltr (left-to-right) and rtl (right-to-left). |

16 What are HTML entities? Medium

HTML entities are codes used to represent special characters in HTML that cannot be easily typed or displayed. Example: &amp represents (&)

17 What are HTML ARIA attributes and how are they used? Medium

| Attribute | Description | Example |
| ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- |
| aria-label | Provides a short, descriptive label for an element that isn't already provided by its text content or associated label element. | <button aria-label="Search">🔍</button> |
| aria-describedby | References another element that provides additional information about the current element, such as instructions or help text. | <input type="text" aria-describedby="name-help"> <div id="name-help">Enter your full name</div> |
| aria-required | Indicates which form fields are mandatory and must be filled out before the form can be submitted. | <input type="text" aria-required="true"> |
| aria-expanded | Indicates whether a collapsible element like an accordion or dropdown menu is currently expanded or collapsed. | <button aria-expanded="true" aria-controls="menu">Menu</button> <div id="menu">...</div> |
| aria-disabled | Indicates whether an element is currently disabled or not, such as a disabled button. | <button aria-disabled="true">Submit</button> |
| aria-checked | Indicates whether a checkbox or radio button is currently checked or not. | <input type="checkbox" aria-checked="true"> |
| aria-haspopup | Indicates that an element has a pop-up or dropdown menu associated with it. | <button aria-haspopup="true" aria-controls="menu">Menu</button> <div id="menu">...</div> |
| aria-selected | Indicates that an element is currently selected or highlighted, such as a selected item in a list | <li aria-selected="true">Item 1</li> |
| aria-hidden | Indicates that an element is currently hidden or not visible to users, such as content that is only revealed when certain conditions are met. | <div aria-hidden="true">Hidden content</div> |

<br />

---

18 What are the possible ways to apply CSS styles to a web page? Medium

There are three standard methods to apply CSS styling to an HTML document:

### 1. External Stylesheet (Recommended Standard):
Link an external .css file in the <head> using <link>:

<link rel="stylesheet" href="/css/styles.css">

*Benefits:* Clean separation of concerns, browser caching across multiple pages, minimal HTML file sizes.

### 2. Internal / Embedded Styles:
Define rules inside a <style> block within the document <head>:

<style>
  body { font-family: system-ui, sans-serif; }
</style>

*Use case:* Single-page email templates or critical path CSS injected for sub-second above-the-fold render speeds.

### 3. Inline Styles:
Apply styles directly to an element via the style attribute:

<p style="color: #2563eb; font-weight: 600;">Highlighted Note</p>

*Drawbacks:* Highest specificity, impossible to cache, clutters markup, prohibits media queries and pseudo-classes (:hover).

19 What are some new features in CSS3? Medium

CSS3 modularized the styling specification, introducing transformative layout engines and dynamic visual capabilities:

### Breakthrough Features in CSS3:

  1. Modern Layout Engines: Flexbox (1-dimensional) and CSS Grid (2-dimensional) replaced fragile float hacks and table layouts.
  2. Visual Effects: border-radius (rounded corners), box-shadow (depth/elevation), linear-gradient() / radial-gradient().
  3. Motion & Transitions: Native transition and @keyframes animations executed on GPU composite layers.
  4. Responsive Media Queries: @media (max-width: 768px) enabling mobile-first fluid web layouts.
  5. Color Formats: rgba(), hsla(), and modern wide-gamut colors (oklch(), color(display-p3)).
  6. Custom Properties (CSS Variables): --primary-color: #2563eb; enabling dynamic real-time theme switching.
20 What are the CSS selectors? Medium

CSS selectors declare which HTML elements a set of CSS rules applies to:

### Selector Categories:

  1. **Universal Selector (*)**: Matches every DOM element.
  2. Type / Tag Selector (h1, p): Matches elements by HTML tag name.
  3. Class Selector (.btn-primary): Matches elements possessing that class.
  4. ID Selector (#header): Matches the unique element with that ID.
  5. Attribute Selectors: [data-state="active"], [href^="https://"].
  6. Combinators:
  • Descendant (div p): All paragraphs inside div.
  • Child (div > p): Immediate direct child paragraphs only.
  • Adjacent Sibling (h2 + p): The paragraph immediately following an h2.
  • General Sibling (h2 ~ p): All paragraphs sharing the same parent following h2.
  1. Pseudo-Classes (:hover, :focus, :nth-child()) and Pseudo-Elements (::before, ::after).
Showing 20 of 68 questions

Frequently Asked Questions About HTML & CSS Interviews

What do hiring managers evaluate in HTML & CSS technical rounds?

Technical interviewers look for foundational fluency, idiomatic syntax, clarity when communicating complex logic, and awareness of performance trade-offs (e.g. memory footprint, render performance, and network latency) in production environments.

What are the best interview tips for practicing HTML & CSS questions?

Use active recall: summarize each answer in your own words before revealing the model solution. Focus on explaining why a certain approach is chosen rather than just memorizing code syntax.