HTML & CSS Interview Questions and Answers
Semantics, accessibility, layout systems, responsive design and modern CSS.
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 What is the CSS box model? Easy
Every element is a box made of four layers: content, padding, border and margin. By default width applies to the content box, so padding and border are added on top (content-box). box-sizing: border-box makes width include padding and border, which is why most codebases set it globally.
*, *::before, *::after { box-sizing: border-box; }
Margin collapsing, percentage widths relative to the containing block, and negative margins are common follow-up questions.
2 What are semantic HTML elements and why do they matter? Easy
Semantic elements describe their meaning rather than only their appearance: header, nav, main, article, section, aside, footer, figure, time, button.
Benefits:
- Accessibility: screen readers announce landmarks and roles, letting users navigate by region.
- SEO: crawlers understand document structure and importance.
- Maintainability: code is self-documenting.
- Free behaviour: button, a, input and form come with keyboard handling and built-in semantics, whereas clickable divs require manual ARIA and key handlers.
Rule: use the native element that matches the meaning; only add ARIA when no native element exists, and never override correct native semantics.
3 What is HTML and what are it's basic components? Easy
HTML (Hyper Text Markup Language) is the standard markup language for creating web pages. It's basics components includes element, tags and attribute.
4 What is the purpose of Doctype in HTML? Easy
The Doctype declaration specifies the type of document being used and tell the web browser how to interpret the pages content. It is located at the top of the HTML document.
5 What is semantic HTML? Easy
Semantic HTML uses specific HTML elements to provide additional information about the structure and content of the page, making it more accessible and easy to read.
6 What is the difference between div element and span element? Easy
The div element is a block-level element that is used to group and organize other HTML elements while span element is an inline-element that is used to apply style or attribute to a specific part of a block-level element.
7 What is the difference between <b> and <strong> tags in HTML? Easy
The <B> tag is used to apply bold formatting to text, while the <strong> tag is used to indicate that the text is important and carries stronger semantic meaning than <b>.
8 What is the difference between a GET request and POST request? Easy
The GET request is used to retrieve data from a web server, while a POST request is used to submit data to a web server. GET requests are less secure and have limit on the amount of data that can be sent while POST request have no limit and are more secure.
9 How do you create a hyperlink in HTML? Easy
Hyperlinks are created using the anchor element (<a>) paired with the essential href (Hypertext Reference) attribute:
<!-- External Link with Security Hardening -->
<a href="https://hirextech.com/categories" target="_blank" rel="noopener noreferrer">
Explore Technical Interview Categories
</a>
<!-- Internal Anchor Navigation -->
<a href="#salary-insights">Jump to Salary Section</a>
<!-- Email and Telephone Triggers -->
<a href="mailto:support@hirextech.com">Email Support</a>
<a href="tel:+18005550199">Call Support</a>
### Critical Security Best Practice:
Whenever using target="_blank" to open a new browser tab, you must include rel="noopener noreferrer". Without this, the newly opened tab can access the original window's window.opener object, introducing vulnerability to reverse tabnabbing phishing attacks.
10 What is the purpose of the alt attribute in HTML? Easy
The alt attribute is used to provide a text description of an image for users who are unable in to see the image, such as those who use screen readers.
11 What is the difference between <link> tag and <a> tag? Easy
The anchor tag <a> is used to create a hyperlink to another web page or to a certain part of a web page and these links are clickable, whereas, link tag <link> defines a link between a document and external resource and these are not clickable.
12 What is the canvas element in HTML5? Easy
The <canvas> element provides a scriptable bitmap drawing surface in HTML. It acts as an empty resolution-dependent drawing container that JavaScript manipulates via procedural drawing APIs:
### Rendering Contexts:
- 2D Context (
getContext('2d')): Used for drawing paths, boxes, text, gradients, and 2D games. - WebGL / WebGL2 (
getContext('webgl')): Hardware-accelerated 3D graphics rendering powered by the client GPU (used by Three.js and Babylon.js).
### Code Example:
<canvas id="myCanvas" width="400" height="200"></canvas>
<script>
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
// Draw rectangle
ctx.fillStyle = '#2563eb';
ctx.fillRect(20, 20, 150, 100);
</script>
*Difference from SVG:* Canvas renders pixels onto a raster bitmap (faster for thousands of moving particles or video frame manipulation), whereas SVG is an XML DOM tree of vector shapes (infinitely scalable and individually inspectable in the DOM).
13 What is an HTML form? Easy
An HTML form (<form>) is a document container designed to collect user input and transmit it securely to a web server or client-side JavaScript handler.
### Core Form Anatomy:
<form action="/api/feedback" method="POST" enctype="application/x-www-form-urlencoded">
<label for="username">Full Name:</label>
<input type="text" id="username" name="username" required>
<button type="submit">Submit Feedback</button>
</form>
### Essential Form Attributes:
action: Target URL endpoint where data is sent upon submission.method: HTTP verb used for transmission:GET: Appends form data as URL query parameters (?name=John), suitable for search queries.POST: Packages data in the HTTP request body, required for sensitive data or database mutations.enctype: Encoding format (multipart/form-datais mandatory when uploading files).
14 What is the difference between HTML form's "action" and "method" attributes? Easy
The "action" attribute specifies the URL to which the form data is submitted, while the "method" attribute specifies the HTTP method when submitting the form data(either "GET" or "POST").
15 What is the purpose of <head> tag? Easy
The <head> tag in HTML is used to provide metadata about document, such as title of page, links and other information that is not directly displayed on the web page. This information is used by browser and search engine to understand the content and structure of the web page.
16 What is the purpose of the <meta> tag in HTML? Easy
The <meta> tag is used to provide additional information about the webpage, such as author, keywords, description which is used by search engines to understand the content of the page.
17 What is the purpose of the <script> tag in HTML? Easy
The <script> tag is either used to embed client-side script(Javascript), or it points to an external script file through the src attribute.
18 What is the purpose of the viewport meta tag? Easy
The viewport meta tag informs mobile browsers how to control the page's dimensions and scaling relative to the physical device screen:
<meta name="viewport" content="width=device-width, initial-scale=1.0">
### Why It Is Mandatory for Responsive Web Design:
- Disables Desktop Zoom Emulation:
Without this tag, mobile browsers assume the website is built for a 980px desktop monitor and scale the page down, resulting in microscopic, unreadable text.
width=device-width: Sets the width of the virtual viewport to match the physical screen width of the device in CSS pixels.initial-scale=1.0: Establishes a 1:1 ratio between CSS pixels and device-independent pixels upon initial page load.
*Accessibility note:* Avoid setting user-scalable=no or maximum-scale=1.0 as doing so prevents visually impaired users from zooming in, violating WCAG accessibility guidelines.
19 What is the purpose of the <noscript> tag in HTML? Easy
The <noscript> tag in used to display text for those browsers which does not support script tag or the browser disabled the script by user.
20 What is the purpose of the <fieldset> tag in HTML? Easy
The <fieldset> tag is used in HTML forms to logically group related form controls and labels together, both visually and semantically:
<fieldset>
<legend>Billing Address Information</legend>
<label for="street">Street Address:</label>
<input type="text" id="street" name="street">
<label for="zip">Postal Code:</label>
<input type="text" id="zip" name="zip">
</fieldset>
### Key Advantages:
- Accessibility (Screen Readers):
The child <legend> provides context. Screen readers announce the legend before each input within the fieldset, which is crucial for grouped radio buttons or complex shipping forms.
- Mass Disabling:
Setting <fieldset disabled> automatically disables all form controls nested inside it simultaneously, eliminating the need to set disabled on every input individually.
21 What is the difference between HTML tag and HTML element? Easy
HTML tag is just opening or closing entity. For example <p> and </p> are called HTML tags. <br />
HTML element consists of opening tag, closing tag and content(optional for content-less tags). For example: <p> This is the content </p>, this complete thing is called HTML element.
22 What is HTML5 web storage? Easy
HTML5 Web Storage is a mechanism in modern web browsers that allows web applications to store data locally within the user's browser. It provides two storage options: Local Storage and Session Storage.
23 What is the use of "target" attribute in HTML? Easy
The target attribute on <a>, <form>, or <area> tags specifies where to display the linked document or form submission response:
### Permitted Keywords:
_self(Default): Opens the document in the current browsing context (same tab/window)._blank: Opens the document in a new browser tab or secondary window._parent: Opens the linked document in the parent browsing context (useful when breaking out of an<iframe>)._top: Opens the linked document in the topmost browsing context, dismissing all nested frames.frameName: Opens the document inside a specifically named iframe:<iframe name="preview">.
*Security Best Practice:* Always combine target="_blank" with rel="noopener noreferrer" to protect against window.opener exploits.
24 What is the use of "em" tag? Easy
The "em" tag is a semantic tag which is used to apply emphasis to a word or phrase within a paragraph. <br />
Example: The sentence "I really enjoyed cycling" could be written using the "em" tag to emphasize the word "really": "I <em>really </em> enjoyed the concert last night."
25 What is the purpose of <header> tag? Easy
The <header> tag is used to defined the header section of a webpage which includes site logo, navigation menu, and other introductory content.
26 What is the purpose of <nav> tag? Easy
The <nav> element represents a section of a page whose purpose is to provide navigation links, either within the current document or to external pages:
<nav aria-label="Main Navigation">
<ul>
<li><a href="/categories">All Categories</a></li>
<li><a href="/mock-interview">Mock Practice</a></li>
<li><a href="/pricing">Pro Access</a></li>
</ul>
</nav>
### Semantic Importance:
- Screen Readers & Assistive Tech: Screen readers identify
<nav>as a landmark region, enabling users with visual impairments to bypass header banners and jump directly to site navigation using landmark shortcut keys. - SEO: Search engine crawlers (like Googlebot) prioritize
<nav>links to map site hierarchy and identify primary internal link graphs. - *Usage note:* Not all links belong in
<nav>. It should be reserved for major navigational blocks, not footer legal disclaimers.
27 What is the purpose of <main> tag? Easy
The <main> element represents the dominant, central content unique to the document.
### Rules of Usage:
- Content inside
<main>should be unique to that specific page and exclude content repeated across multiple pages (such as global navigation links, copyright footers, sidebars, and logo banners). - A document must not have more than one non-hidden
<main>element. - It must not be nested inside
<header>,<footer>,<nav>, or<article>.
### Accessibility Role:
Exposes an explicit ARIA landmark (role="main"), enabling keyboard and screen reader users to skip repeated navigation bars and jump straight to the primary topic.
28 What is the purpose of <article> tag? Easy
The <article> element represents a complete, self-contained composition in a document that is independently distributable or reusable (e.g. in syndication, RSS feeds, or news aggregators):
### Typical Use Cases:
- A technical interview question and solution entry
- A blog post or news article
- A forum post or user comment
- An interactive product card
### Structure Example:
<article class="interview-question">
<header>
<h2>What is the event loop in JavaScript?</h2>
<span class="difficulty-badge">Hard</span>
</header>
<div class="solution-body">
<p>Detailed architectural explanation...</p>
</div>
<footer>
<time datetime="2026-09-20">Updated Sept 2026</time>
</footer>
</article>
29 What is the purpose of <section> tag? Easy
The <section> element represents a standalone thematic grouping of content, typically with a heading (<h2>-<h6>):
### How <section> Differs from <div> and <article>:
<div>: Has no semantic meaning; purely used as a styling wrapper or flex/grid layout container.<section>: Represents a logical chapter or thematic block (e.g. "Introduction", "Code Example", "Common Pitfalls", "Interviewer Evaluation Rubric").<article>: Represents an independently distributable piece of content that could stand completely alone outside the page context.
### Semantic Rule of Thumb:
If the content represents a logical outline heading in the document's table of contents, wrap it in a <section>.
30 What is the purpose of <aside> tag? Easy
The <aside> tag is used to define content that is related to the main content of a webpage, but is not directly part of it. It is often used to provide additional information to the main content.
31 What is the purpose of <footer> tag? Easy
The <footer> tag is used to define the footer section of a webpage which contains copyright information, contact details, and other legal content.
32 What is the purpose of <figure> tag? Easy
The <figure> element represents self-contained content, optionally accompanied by a caption (<figcaption>), that is referenced as a single unit from the main text flow:
<figure>
<img src="/diagrams/event-loop.webp" alt="JavaScript Call Stack and Event Queue Diagram">
<figcaption>Figure 1: Visual representation of the Microtask vs Macrotask Queue.</figcaption>
</figure>
### Advantages:
- The content can be moved away from the primary text flow (e.g. into an appendix or sidebar) without affecting the document's flow.
- Accommodates not only images, but also code blocks, diagrams, data tables, audio clips, or quotes.
33 What is the purpose of <figcaption> tag? Easy
The <figcaption> element provides a semantic caption or legend for its parent <figure> element:
### Usage Rules:
- Must be nested as either the first child or the last child of a
<figure>element. - Automatically associates the caption text with the media element for assistive technologies, allowing screen readers to announce the caption as the official description of the figure.
34 What is the purpose of <blockquote> tag? Easy
The <blockquote> tag is used to indicate that a section of text is being quoted from another source. It is used to highlight a particularly important quote.
35 What is <datalist> tag? Easy
The <datalist> tag is new addition to HTML5, and it is used to provide a list of pre-defined options for an input field. It allows us to create dropdown list of options.
36 What is the use of <option> tag? Easy
The <option> tag is used to define an option in a dropdown list. The 'value' attribute in <option> tag is specifies the value of the option that will be submitted when the form is submitted.
37 What is the purpose of the "data-\*" attribute in HTML? Easy
The data=\* attribute allows us to store additional information about an HTML element that is not otherwise displayed on the page, but may be useful to scripts that interact with the page.
38 What is the purpose of <legend> tag? Easy
The <legend> tag provides semantic caption or title for a <fieldset> element. It is optional but better for better to have for accessibility.
39 What is the purpose of the <picture> element in HTML5, and how is it used to optimize images? Easy
The <picture> element in HTML5 is used to provide multiple versions of an image at different resolutions or sizes, and allows the browser to choose the best version to display based on the user's device and viewport size.
40 What is CSS? Easy
CSS stands for Cascading Style Sheets. CSS is used to define styles for web pages, including the design, layout and variations in display for different devices and screen sizes.
41 What is universal selector in CSS? Easy
The universal selector is a css selector that can be used to apply styles to all elements on a page or to reset styles for all elements to their default values
42 What is the difference between margin and padding in CSS? Easy
Margin is the space between the border of an element and the surrounding elements, while padding is the space between the content of an element and its border.
43 What is the CSS position property and its values? Easy
The CSS position property controls how an element is positioned on a page. The possible values are static, relative, absolute, fixed, and sticky
44 What is the difference between absolute and relative positioning in CSS? Easy
Relative positioning moves an element relative to its current position without affecting the position of other elements, while absolute positioning positions an element relative to its closest parent element, potentially affecting the position of other elements.
45 What is the CSS clear property? Easy
The CSS clear property controls whether an element is allowed to float next to another element or not. The possible values include left, right, both, and none. When an element is cleared, it will be moved below any floated elements.
46 What is the CSS z-index property? Easy
The CSS z-index property controls the stacking order of elements on a page. Elements with a higher z-index value are displayed on top of elements with a lower z-index value. The default value of z-index is auto.
47 What is CSS animation? Easy
A CSS animation allows elements to transition smoothly between different style configurations over time using keyframes, without writing custom JavaScript animation loops:
@keyframes pulse {
0% { transform: scale(1); opacity: 1; }
50% { transform: scale(1.05); opacity: 0.8; }
100% { transform: scale(1); opacity: 1; }
}
.badge-live {
animation: pulse 2s infinite ease-in-out;
}
### Core Animation Properties:
animation-name: The@keyframesidentifier.animation-duration: Total time for one complete cycle (e.g.300ms,2s).animation-timing-function: Acceleration curve (ease,linear,cubic-bezier()).animation-iteration-count:1,3, orinfinite.animation-fill-mode:forwardsretains the styles of the final keyframe after completion.
48 What is transition in CSS? Easy
A transition in CSS is a way to create animation effects when a property of an HTML element changes, allowing developers to smoothly animate changes to an element's style over a specified duration.
49 What is the difference between linear and radial gradient in CSS? Easy
A linear gradient creates a smooth transition between two or more colors in a straight line while the radial gradient creates a smooth transition between two or more colors in a circular shape.
50 What is flexbox? Easy
Flexbox is a CSS3 layout module which provides more flexible and efficient way to align arrange and align the elements within the container. It is widely supported by the modern web browser.
51 What is the difference between flex-grow and flex-shrink properties in Flexbox? Easy
flex-grow is a property in Flexbox that specifies how much a flex item should grow relative to the other items in the container, while flex-shrink specifies how much a flex item should shrink relative to the other items when there is not enough space available in the container.
52 What is the difference between flex-wrap: nowrap and overflow: hidden in CSS? Easy
flex-wrap: nowrap prevents flex items from wrapping to the next line when they overflow the container, while overflow: hidden hides any content that overflows the container's boundaries.
53 What is the `gap` property in Flexbox, and how is it used to add spacing between flex items? Easy
The gap property in Flexbox sets the spacing between flex items, both horizontally and vertically. It is a shorthand for row-gap and column-gap.
54 What is CSS grid? Easy
CSS Grid Layout is a powerful two-dimensional layout system designed for simultaneously controlling both rows and columns:
.dashboard-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
gap: 1.5rem;
}
### Grid vs Flexbox:
- Flexbox: One-dimensional (handles items along either a row OR a column).
- CSS Grid: Two-dimensional (positions items across intersecting horizontal and vertical tracks).
### Key Terminology:
- Grid Container: Element with
display: grid. - Grid Tracks: Columns and rows defined via
grid-template-columnsandgrid-template-rows. - Fractional Unit (
fr): Represents a fraction of the available free space in the grid container. - Grid Template Areas: Named layout regions (
"header header" "sidebar main" "footer footer").
55 What is the difference between grid-row and grid-column in CSS Grid? Easy
grid-row is used to position an item within a row, while grid-column is used to position an item within a column. Both properties can take a value of either a number or a named grid line.
56 What is a CSS transition? Easy
A CSS transition enables you to create gradual, interpolated animations between two visual states of an element when a CSS property value changes (such as on :hover, :focus, or dynamic class toggling):
.cta-button {
background-color: #2563eb;
color: #ffffff;
transition: background-color 0.25s ease-in-out;
}
.cta-button:hover {
background-color: #1d4ed8;
}
### The 4 Transition Sub-Properties:
transition-property: Names which properties to animate (background-color,transform,opacity).transition-duration: Duration of animation (200ms,0.5s).transition-timing-function: Mathematical easing curve (ease,linear,cubic-bezier).transition-delay: Delay before animation starts.
57 What is the purpose of the `transition-property` property in CSS transitions? Easy
The transition-property CSS property specifies the exact names of the CSS properties that should animate when their values change:
/* Recommended: Explicitly named properties */
.box {
transition-property: transform, opacity;
transition-duration: 300ms;
}
### Why You Should Avoid transition-property: all:
- Performance Overhead: Specifying
allforces the browser to monitor and interpolate every single animatable property on every DOM reflow, degrading rendering performance. - Unintended Side Effects: Accompanying properties (such as width or margins) might animate unexpectedly during screen resizing, resulting in jittery UI layouts.
58 What is the function of the `transition-timing-function` property in CSS transitions? Easy
The transition-timing-function property specifies the rate of change of the transition over time. This can be used to control the speed of the transition and how it accelerates and decelerates. Example: ease-in, ease, ease-out.
59 What is the difference between the `translate()` and `rotate()` functions? Easy
The translate() function is used to move an element along the x-axis and/or y-axis, while the rotate() function is used to rotate an element clockwise or counterclockwise around a given point.
60 What is the difference between RGB and RGBA colors? Easy
RGBA is similar to RGB, but it includes an additional alpha value that represents the opacity of the color. The alpha value is a number between 0 and 1, with 0 being completely transparent and 1 being completely opaque.
61 What is CSS filter? Easy
CSS filters are a set of visual effects that can be applied to HTML elements using CSS. Filters can be used to adjust the appearance of an element in various ways, such as changing its color, blurring or sharpening it, adjusting its brightness or contrast, and more.
62 What is a CSS sprite? Easy
A CSS sprite is a technique used to combine multiple images into a single image file, reducing the number of HTTP requests required to load the page and improving loading times.
63 What is the :not() pseudo-class used for in CSS? Easy
The :not() functional pseudo-class (known as the negation pseudo-class) matches elements that do not match the selector argument provided inside its parentheses:
/* Style all buttons except disabled ones */
button:not(:disabled) {
cursor: pointer;
background-color: #2563eb;
}
/* Style list items except the last one with a divider */
li:not(:last-child) {
border-bottom: 1px solid #e2e8f0;
}
/* CSS Selectors Level 4: Supports comma-separated selector lists */
p:not(.lead, .disclaimer) {
font-size: 1rem;
}
*Note:* The specificity of :not() is determined by the highest specificity selector inside its argument list.
64 What is the :visited pseudo-class used for in CSS? Easy
The :visited pseudo-class styles anchor links (<a>) that the user has already navigated to in their browser history:
a:visited {
color: #7c3aed; /* Purple indicator for visited links */
}
### Strict Browser Privacy Restrictions:
To prevent malicious websites from sniffing a user's browsing history by styling links and reading back computed styles with JavaScript, modern browsers enforce strict security restrictions on :visited:
- Only color-related properties are permitted:
color,background-color,border-color,outline-color, and SVGfill/stroke. - Alpha transparency components are ignored.
- JavaScript methods like
getComputedStyle()will always lie and report the unvisited color.
65 What is the :active pseudo-class used for in CSS? Easy
The :active pseudo-class represents an element in the process of being activated by the user.
### When Is It Triggered?
- The moment a user presses and holds the primary mouse button down on an element, lasting until the mouse button is released.
- During physical touch tap on mobile touchscreen displays.
### Classic Button Press Animation:
.btn {
transform: scale(1);
transition: transform 0.1s ease;
}
.btn:active {
transform: scale(0.96); /* Provides physical tactile click sensation */
}
### The LVHA Ordering Rule:
When styling links, define pseudo-classes in this exact order to prevent cascade overriding:
:link:visited:hover:active(LoVe HAte mnemonic)
66 What is the :lang() pseudo-class used for in CSS? Easy
The lang() pseudo-class is used to target elements based on the language attribute of the HTML document. For example, you can use :lang(en) to target all elements in English, or :lang(fr) to target all elements in French.
67 What is the :checked pseudo-class used for in CSS? Easy
The :checked pseudo-class is used to target form elements that have been selected by the user, such as checkboxes or radio buttons. This can be used to change the appearance or behavior of the selected element.
68 What is the @media rule in CSS? Easy
The @media rule in CSS allows developers to apply styles to a web page based on the size of the device or screen being used to view it, making it more responsive.
69 What is the difference between fluid and fixed layouts in CSS? Easy
A fluid layout in CSS adjusts its width and height based on the size of the screen, while a fixed layout has a set width and height. Fluid layouts use percentages to set their dimensions, while fixed layouts use pixels.
70 What is the difference between min-width and max-width in CSS media queries? Easy
In CSS media queries, min-width sets the minimum screen width at which a set of styles will be applied, while max-width sets the maximum screen width at which a set of styles will be applied. For example, if you use min-width: 768px, the styles will only be applied to screens that are 768 pixels wide or larger, while if you use max-width: 768px, the styles will only be applied to screens that are 768 pixels wide or smaller.
71 What is the difference between responsive and adaptive design in CSS? Easy
Responsive design in CSS adapts to different screen sizes and devices by using flexible grids, fluid images, and media queries to adjust the layout and content of the website. Adaptive design in CSS, on the other hand, uses predefined layout sizes and breakpoints to adjust the layout and content based on the screen size and device being used.
72 What is the overflow property in CSS used for? Easy
The overflow property specifies what should happen if content overflows an element’s box. It's possible values are: auto, none, scroll, visible.
73 What is the difference between `visibility:hidden` and `display:none`? Easy
visibility:hidden means the tag is not visible, but the space is allocated for it on the page. display:none means the tag will not appear at all and there will be no space allocated for it between the other tags.
74 What is the purpose of CSS content property? Easy
The content property is used exclusively in conjunction with the ::before and ::after pseudo-elements to generate decorative or supplementary visual content without adding extra HTML DOM elements:
/* Generating an icon or badge indicator */
.required-field::after {
content: " *";
color: #ef4444;
font-weight: bold;
}
/* Clearing floats (Micro clearfix) */
.clearfix::after {
content: "";
display: block;
clear: both;
}
*Accessibility Note:* Content generated via CSS content was historically invisible to screen readers; today, screen readers may read it. Never insert critical textual information solely via content.
75 What is the "line-height" property in CSS? Easy
The line-height property defines the height of an inline line box, determining the vertical distance between baselines of consecutive lines of text:
### Value Formats:
- Unitless Number (Best Practice):
body { line-height: 1.5; }
A unitless number acts as a proportional multiplier of the element's current font-size. Child elements inherit the multiplier rather than a fixed computed pixel size, preventing text overlapping if children declare larger font sizes.
- Lengths (
px,rem):line-height: 24px;(Rigid, breaks on dynamic font scaling). - Percentages (
150%): Can cause inheritance calculation issues in nested headers.
76 What is specificity in CSS? Easy
Specificity in CSS is a way of determining which CSS rule applies to an element. It is based on the number of selectors and their types in a CSS rule. Specificity is calculated using a formula: inline styles have the highest specificity, followed by IDs, classes, and then elements.
77 What is the word-wrap property in CSS3? Easy
The word-wrap property (renamed in modern CSS specifications to overflow-wrap) specifies whether the browser may break long unbreakable character sequences (such as lengthy URLs, hash strings, or file paths) onto a new line to prevent horizontal layout overflow:
.card-content {
/* overflow-wrap is the standard; word-wrap is legacy alias */
overflow-wrap: break-word;
word-wrap: break-word;
}
### Difference from word-break: break-all:
overflow-wrap: break-wordonly breaks a word if the entire word cannot fit onto a line by itself.word-break: break-allaggressively breaks words at the exact right margin boundary regardless of whether the word could fit unbroken on the next line.
78 What is Tailwind CSS? Easy
TailwindCSS is a utility-first CSS framework that provides pre-defined CSS classes that can be used to rapidly build custom user interfaces.
79 What is CSS preprocessor? Easy
A CSS preprocessor is a tooling program that extends standard CSS syntax with programmatic capabilities (such as variables, functions, mixins, and nested rules), compiling the code into standard, browser-compatible CSS before runtime:
### Popular Preprocessors:
- Sass / SCSS: The industry standard preprocessor.
- Less: JavaScript-based preprocessor.
- Stylus: Expressive, Python-inspired syntax.
### Key Preprocessor Features:
- Nesting: Structuring selectors to mirror HTML hierarchy.
- Mixins: Reusable blocks of styles passed with arguments.
- Partials & Modules: Splitting styles into files (
_variables.scss,_buttons.scss) and importing via@use. - *Modern Context:* Many native CSS features (CSS variables, native CSS nesting
@scope, color functions) have adopted ideas originally introduced by preprocessors.
80 What is the difference between a CSS preprocessor and a post-processor? Easy
A CSS preprocessor generates CSS code from source code written in a higher-level scripting language, whereas a post-processor takes existing CSS code and applies transformations or optimizations to it. In other words, a preprocessor is used during development, while a post-processor is used after development to optimize performance.
81 What is SASS? Easy
Sass is a CSS preprocessor that adds functionality to CSS, such as variables, nesting, and more. It allows us to write more efficient code and simplifies task like browser compatibility.
82 What is the difference between SASS and SCSS? Easy
Sass and SCSS are both CSS pre-processors and are very similar, but they have different syntax. Sass has a more concise and less verbose syntax, with no curly braces and no semicolon whereas SCSS has a syntax that is almost identical to standard CSS, with curly braces and semicolons
83 What is SASS nesting? Easy
Sass nesting is a feature that allows us to write CSS selectors that are nested within one another which makes our code easier to read and understand.
84 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; }
85 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.
86 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.
87 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".
88 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>
89 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:
text: Standard single-line plain text entry.password: Obscures characters with dots/asterisks for credential security.email: Validates email format and displays@symbol on mobile soft keyboards.number: Restricts entry to digits with optionalmin,max, andstepattributes.tel: Mobile phone number entry triggering numeric telephone keypad.url: Enforces valid URL protocol prefixes (http://orhttps://).checkbox: Toggle option for multiple selectable choices.radio: Mutually exclusive selection within a sharednamegroup.file: File upload picker withacceptandmultipleattribute support.date,time,datetime-local: Native calendar and clock pickers.range: Visual slider control between numeric bounds.color: Native hex color picker dialog.hidden: Stores invisible state transmitted upon form submission.submit,reset,button: Action buttons trigger submission or reset events.
90 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.
91 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:
- The
sandboxAttribute: Highly recommended when embedding third-party content. It restricts execution of untrusted scripts, form submissions, and popups. X-Frame-Options& CSPframe-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.
92 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:
- Semantic Structure Elements: Introduced
<header>,<footer>,<article>,<section>, and<nav>to replace generic<div>tags, vastly improving SEO and accessibility. - Native Multimedia Support: Introduced
<video>and<audio>tags for native media playback without external browser plugins. - Interactive Graphics (
<canvas>& SVG): Native 2D/3D hardware-accelerated rendering directly in the browser. - Client-Side Storage: Replaced restrictive 4KB cookies with
localStorage(5-10MB) and IndexedDB for offline Progressive Web Apps (PWAs). - Modern Form Controls: Native validation attributes (
required,pattern) and specialized input types (email,date,number). - Web APIs Integration: Geolocation API, WebSockets, Web Workers (background threading), and Drag-and-Drop.
93 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.
94 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.
95 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.
96 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.
97 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 |
98 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). |
99 What are HTML entities? Medium
HTML entities are codes used to represent special characters in HTML that cannot be easily typed or displayed. Example: & represents (&)
100 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 />
---
101 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).
102 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:
- Modern Layout Engines: Flexbox (1-dimensional) and CSS Grid (2-dimensional) replaced fragile float hacks and table layouts.
- Visual Effects:
border-radius(rounded corners),box-shadow(depth/elevation),linear-gradient()/radial-gradient(). - Motion & Transitions: Native
transitionand@keyframesanimations executed on GPU composite layers. - Responsive Media Queries:
@media (max-width: 768px)enabling mobile-first fluid web layouts. - Color Formats:
rgba(),hsla(), and modern wide-gamut colors (oklch(),color(display-p3)). - Custom Properties (CSS Variables):
--primary-color: #2563eb;enabling dynamic real-time theme switching.
103 What are the CSS selectors? Medium
CSS selectors declare which HTML elements a set of CSS rules applies to:
### Selector Categories:
- **Universal Selector (
*)**: Matches every DOM element. - Type / Tag Selector (
h1,p): Matches elements by HTML tag name. - Class Selector (
.btn-primary): Matches elements possessing that class. - ID Selector (
#header): Matches the unique element with that ID. - Attribute Selectors:
[data-state="active"],[href^="https://"]. - Combinators:
- Descendant (
div p): All paragraphs insidediv. - Child (
div > p): Immediate direct child paragraphs only. - Adjacent Sibling (
h2 + p): The paragraph immediately following anh2. - General Sibling (
h2 ~ p): All paragraphs sharing the same parent followingh2.
- Pseudo-Classes (
:hover,:focus,:nth-child()) and Pseudo-Elements (::before,::after).
104 Explain the difference between classes and IDs in CSS. Medium
Classes are used to group together elements with similar styles, while IDs are used to target specific elements on a page. IDs must be unique, while classes can be used multiple times on a page.
105 Explain box model in CSS. Medium
The box model in CSS is a way of representing elements as boxes with content, padding, borders, and margins. The content area is the actual content of the element, the padding is the space between the content and the border, the border is a line around the element, and the margin is the space between the border and the surrounding elements.
106 Explain the CSS display property and its values. Medium
The CSS display property controls how an element is displayed on a page. The possible values are block, inline, inline-block, none, and others.
107 Explain the CSS float property and its values. Medium
The CSS float property controls the alignment of an element in a page layout. The possible values include left, right, none, and inherit. When an element is floated left or right, other elements will flow around it.
108 What are CSS pseudo-classes? Give some examples. Medium
CSS pseudo-classes are selectors that target elements based on their state or position in the document. Some examples include :hover, :active, :focus, :first-child, :last-child, and :nth-child.
109 How do you define a CSS animation? Medium
We can define CSS animation by creating a set of keyframes that specify the start and end states of an animation. We can apply the animation to an element using the animation property in css.
110 How do you trigger a CSS animation to start and stop? Medium
You can trigger a CSS animation to start and stop using various CSS selectors and events. For example, you can use the :hover pseudo-class to start an animation when a user hovers over an element.
111 How do you create a responsive CSS animation? Medium
We can create responsive CSS animation by using relative units like percentages instead of fixed units like pixels. We can also use media queries to adjust the animation properties based on the size of the viewport.
112 How do you optimize CSS animations for performance? Medium
We can optimize CSS animation for performance by using techniques like reducing the number of elements being animated, minimizing the use of box-shadow and text-shadow, and using transform and opacity instead of top, left, bottom, and right.
113 How do you debug CSS animations and troubleshoot common issues, such as animations not playing or playing too quickly? Medium
We can debug CSS animations by checking for typos or syntax errors, checking browser's compatibility if it supports the property or not, checking for code that may override the animation.
114 Can you specify multiple CSS transitions for an element? Medium
Yes, you can transition multiple CSS properties simultaneously on an element by separating each transition declaration with a comma in the transition shorthand:
.card {
background-color: #ffffff;
transform: translateY(0);
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
/* Multiple distinct transitions */
transition:
background-color 0.2s ease-in,
transform 0.3s cubic-bezier(0.4, 0, 0.2, 1),
box-shadow 0.3s ease-out;
}
.card:hover {
background-color: #f8fafc;
transform: translateY(-4px);
box-shadow: 0 12px 24px rgba(0,0,0,0.15);
}
*Performance Tip:* Restrict transitions to GPU-accelerated properties (transform and opacity) to maintain a smooth 60 FPS without triggering CPU layout reflows.
115 What are gradients in CSS? Medium
It is a property of CSS which allows you to display a smooth transformation between two or more than two specified colors. There are two types of gradients in CSS. They are: Linear gradient and radial gradient.
116 How do you center an element using flexbox? Medium
To center an element using flexbox, we need to set the parent container's display property to flex and use the justify-content & align-items properties with the value of center.
117 How do you use the grid-template-columns and grid-template-rows properties to define the size and number of columns and rows in a grid? Medium
You can use the grid-template-columns and grid-template-rows properties to define the size and number of columns and rows in a grid. For example, you might define a grid with three columns, where the first column is 100 pixels wide, the second column is 50% of the available width, and the third column takes up the remaining space, with the following CSS:
grid-template-columns: 100px 50% 1fr;
118 How do you specify the number of columns in a grid using CSS? Medium
You can specify the number of columns in a grid by using the grid-template-columns property. For example, grid-template-columns: repeat(3, 1fr) will create a grid with three columns that are each one fraction of the available space.
119 How do you align items within a grid using CSS? Medium
You can align items within a grid using the justify-items and align-items properties. justify-items aligns items horizontally within a grid, while align-items aligns items vertically.
120 How do you delay the start of a CSS transition? Medium
You can delay the start of a CSS transition using the transition-delay property. This property specifies the amount of time to wait before starting the transition, in seconds or milliseconds. Example: transition-delay: 1s;
121 How do you apply a transition to multiple properties at once? Medium
You can apply a transition to multiple properties at once by separating the property names with commas in the transition-property property. example, transition-property: background-color, color, opacity;
122 What are CSS 2D Transforms? Medium
CSS 2D Transforms are a set of properties that allow you to transform the position, rotation, scaling, and skewing of an element in two dimensions, without affecting the surrounding elements.
123 Can you use negative values with CSS 2D transforms? If so, what effect do they have? Medium
Yes, you can use negative values with CSS 2D transforms. The effect of negative values depends on the function being used. For example, a negative value for the rotate() function will rotate the element counterclockwise instead of clockwise.
124 What are the properties of CSS 2D transform? Medium
The properties of CSS 2D Transforms are:
- transform: specifies the transformation functions to be applied to an element
- transform-origin: specifies the point around which the transformation should occur
- translate: moves an element along the x-axis and/or y-axis
- rotate: rotates an element clockwise or counterclockwise around a given point
- scale: increases or decreases the size of an element
- skew: skews an element along the x-axis and/or y-axis
125 Can you apply multiple transformations to the same element using CSS 2D transforms? Medium
Yes, you can apply multiple transformations to the same element using CSS 2D transforms. You can do this by separating each transformation function with a space in the transform property.
126 What are some important considerations when using text effects? Medium
Important considerations include making sure the text remains readable and legible, ensuring the effect is appropriate for the overall design, and avoiding overuse of effects.
127 How do you target all even or odd elements using a pseudo-selector in CSS? Medium
You can target alternating rows or elements using the :nth-child() structural pseudo-class with the keywords even or odd:
/* Zebra striping table rows */
tbody tr:nth-child(odd) {
background-color: #ffffff;
}
tbody tr:nth-child(even) {
background-color: #f8fafc;
}
### Algebraic Notation (An + B):
The even keyword is functionally equivalent to :nth-child(2n), matching elements at indices 2, 4, 6, 8...
The odd keyword is equivalent to :nth-child(2n+1), matching elements at indices 1, 3, 5, 7...
128 How do you target the first letter of a text element using a pseudo-selector in CSS? Medium
You target the initial character of a block-level text element using the ::first-letter pseudo-element, commonly used to create decorative editorial drop caps:
.article-intro::first-letter {
font-size: 3.5rem;
font-weight: bold;
float: left;
line-height: 0.8;
margin-right: 0.5rem;
color: #1e293b;
}
*Applicability:* ::first-letter applies only to block containers (such as p, div, article), not to inline elements (span).
129 How do you make images responsive in CSS? Medium
To make images responsive in CSS, you can use the max-width: 100% property, which will make the image scale down proportionally to fit the width of its container while maintaining its aspect ratio.
130 How does calc() work in CSS? Medium
The calc() function allows you to perform dynamic mathematical calculations directly in CSS property values, mixing different units together:
/* Mixing fixed pixels with fluid percentages */
.sidebar-layout {
width: calc(100% - 280px);
margin-left: 280px;
}
/* Fluid responsive typography */
h1 {
font-size: calc(1.5rem + 1vw);
}
### Essential Syntax Rules:
- Supports addition (
+), subtraction (-), multiplication (*), and division (/). - Whitespace is strictly mandatory around
+and-operators: calc(100% - 20px)is valid.calc(100%-20px)is invalid syntax because the browser parses-20pxas a negative number unit.
131 Are quotes mandatory in URL’s? Medium
In CSS url() functional notation, quotes (single ' or double ") are optional for standard alphanumeric URLs, but are mandatory in specific edge cases:
/* Valid without quotes */
background-image: url(/images/bg.webp);
/* Valid with quotes (Recommended best practice) */
background-image: url("/images/bg.webp");
### When Quotes Are Strictly Mandatory:
- If the URL contains whitespace or spaces:
url("my banner image.png"). - If the URL contains parentheses, single quotes, or double quotes.
- In inline SVG Data URIs:
url("data:image/svg+xml;utf8,...").
132 Explain what are web-safe fonts and fallback fonts. Medium
Web-safe fonts are fonts that are commonly installed on most devices and web browsers. Fallback fonts are alternative fonts specified in case the primary font is not available on the user's device.
133 How can we create custom cursor in CSS? Medium
To create a custom cursor in CSS, you can use the "cursor" property and set it to "url" with the path to the image file that you want to use as the cursor.
134 Which property is used to control the scrolling of an image in the background? Medium
The background-attachment property controls whether a background image scrolls along with the enclosing page content or remains fixed in a viewport position:
### Primary Values:
scroll(Default): The background image is fixed relative to the element itself and scrolls with the main page.fixed: The background image is pinned relative to the browser viewport, creating a smooth parallax scrolling effect as content moves over it:
.hero-banner {
background-image: url('/images/pattern.svg');
background-attachment: fixed;
background-position: center;
background-size: cover;
}
local: The background image scrolls with the element's internal scrollable contents.
135 Which CSS property is used to capitalize text or convert text to uppercase or lowercase letters? Medium
The text-transform property controls character capitalization and case formatting without altering the underlying raw HTML string:
### Available Values:
uppercase: Converts all letters to uppercase:HIREXTECH INTERVIEW.lowercase: Converts all letters to lowercase:hirextech interview.capitalize: Capitalizes the first letter of each word:Hirextech Interview.none: Preserves the original casing from the HTML markup.
.table-header {
text-transform: uppercase;
letter-spacing: 0.05em;
font-size: 0.75rem;
}
136 Describe a 'rule set' in CSS. Medium
It is an instruction that tells browser on how to render a specific element on the HTML page. It consists of a selector with a declaration block that follows.
137 How can you create a CSS-only dropdown menu? Medium
A CSS-only dropdown menu can be created by using the "hover" pseudo-class and the "display" property. When the user hovers over a parent element, the "display" property of the child element can be set to "block" or "inline-block" to reveal the dropdown menu.
138 What are the potential drawbacks of using CSS frameworks such as Bootstrap? Medium
While CSS frameworks (Bootstrap, Bulma, Foundation) accelerate early prototyping, they present distinct trade-offs in enterprise production environments:
### Key Drawbacks:
- Unused CSS Bloat: Large framework bundles include thousands of unused utility classes and components, degrading First Contentful Paint (FCP) unless aggressively purged.
- Generic Aesthetic ("Bootstrap Look"): Sites built with default framework themes look visually homogeneous and lack unique brand identity.
- Override Specificity Wars: Customizing deep framework styles often requires fighting high specificity rules or abusing
!important. - HTML Class Clutter: Older frameworks tightly couple HTML markup to presentational class names.
- Modern Trend: Modern teams frequently adopt zero-runtime or utility-first tools (like Tailwind CSS) or component primitives (Radix/Shadcn) which only ship classes actually used in source code.
139 How do you customize TailwindCSS to match a specific design system or brand guidelines? Medium
TailwindCSS provides a configuration file that can be customized to match a specific design system or brand guidelines. This file includes variables for colors, fonts, spacing, and more, which can be adjusted to match the project's needs.
140 Can you explain the difference between utility classes and component classes in TailwindCSS? Medium
Utility classes in TailwindCSS are small, single-purpose classes that provide a specific styling utility, such as padding, margin, or text alignment. Component classes, on the other hand, are larger classes that provide a collection of styles for a specific component, such as a button or card.
141 How do you optimize the file size of TailwindCSS in a production environment? Medium
TailwindCSS provides a purge option that removes any unused classes from the final CSS file, reducing its size. This option should be enabled in a production environment to minimize the CSS file size.
142 What are some common performance issues with TailwindCSS, and how do you optimize performance in your projects? Medium
Common performance issues with TailwindCSS include the size of the CSS file and the number of classes being generated. To optimize performance, it is important to enable the purge option in a production environment, use a caching mechanism to speed up builds, and avoid generating unnecessary classes.
143 Can you describe a situation where you would choose not to use SASS? Medium
A developer might choose not to use Sass if they prefer to stick with standard CSS for simplicity or if they are working on a small project where the added features of Sass may not be necessary.
144 What are variables in SASS? Medium
Variables in Sass (SCSS) store reusable styling values (colors, spacing units, fonts) identified by a dollar sign ($) prefix:
// Definition
$primary-blue: #2563eb;
$font-stack: 'Inter', system-ui, sans-serif;
$border-radius-lg: 12px;
// Usage
.hero-card {
background-color: $primary-blue;
font-family: $font-stack;
border-radius: $border-radius-lg;
}
### Difference Between Sass Variables and Native CSS Custom Properties:
- Sass Variables (
$var): Evaluated at build time. Once compiled to CSS, they become static values. Cannot be dynamically changed via JavaScript at runtime or affected by DOM cascading. - CSS Custom Properties (
--var): Evaluated dynamically by the browser engine at runtime. They participate in the cascade and can be modified on the fly in JavaScript or media queries.
145 What is SASS inheritance? Medium
Inheritance allows us to define a set of styles in one selector, called a "parent", and then extend those styles to another selector, called a "child". Example:
@mixin button-style($bg-color, $text-color) {
background-color: $bg-color;
color: $text-color;
display: inline-block;
padding: 8px 16px;
}
// Use the mixin to create different button styles
.button-primary {
@include button-style(#007bff, #fff);
}
.button-secondary {
@include button-style(#6c757d, #fff);
}
146 How do you use 'if' statements in SCSS? Medium
In SCSS, you can use the @if directive to add conditional logic to your styles. Example:
//declaring variable
$background-color: #333;
body {
@if $background-color == #333 {
background-color: $background-color;
} @else {
background-color: #fff;
}
}
147 What are some common mistakes that developers make when writing CSS, and how do you avoid them? Medium
Writing scalable, maintainable CSS is a hallmark of senior front-end engineering. Common pitfalls include:
### 1. Overusing !important
- *Mistake:* Using
!importantas a quick fix to resolve cascade conflicts. - *Fix:* Understand specificity scoring (Inline > ID > Class/Attribute > Tag) and adopt CSS cascade layers (
@layer) or flat BEM methodology.
### 2. Hardcoding Fixed Pixel Heights on Text Containers
- *Mistake:* Setting
height: 200pxon cards containing dynamic copy, causing text overflow when font size increases or translations expand. - *Fix:* Use
min-heightor allow container dimensions to expand fluidly via Flexbox/Grid.
### 3. Animating Layout-Triggering Properties
- *Mistake:* Animating
top,left,width, orheightwhich triggers CPU layout reflows and browser repaint cycles. - *Fix:* Strictly animate composite properties:
transform(translate3d,scale) andopacity.
### 4. Ignoring Responsive Breakpoints & Accessibility
- *Mistake:* Designing exclusively for desktop 1080p and forgetting mobile viewport meta tags or keyboard
:focus-visiblestyles.
148 How do you balance the need for visual aesthetics with the need for website or application functionality? Medium
I balance the need for visual aesthetics with the need for functionality by designing with the user in mind, testing designs with real users, and incorporating feedback and data into the design process.
149 How do you ensure that your CSS is optimized for search engine optimization (SEO)? Medium
We can ensure CSS is optimized for SEO by minimizing code bloat to improve load time, use relevant class names, avoiding inline styles, etc.
150 How do you ensure that your CSS is scalable and maintainable for large projects? Medium
We can ensure that our CSS is scalable and maintainable for large project by:
- Using proper naming convection for ID and classes.
- Using preprocessor like sass, less, etc.
- Using performance enhancing techniques like lazy-loading, etc.
151 How do you use CSS variables to create more flexible and dynamic designs, and what are some use cases where variables are particularly useful? Medium
CSS variables can improve maintainability and reduce repetition. Variables are particularly useful for theming, creating responsive designs, and making changes to global styles.
152 What are the properties of CSS 3D transform? Hard
The properties of CSS 3D Transforms are:
- transform-style: determines whether an element's children are transformed in 3D space
- perspective: determines the distance between the viewer and the element, affecting the appearance of 3D transforms
- perspective-origin: specifies the origin point of the perspective
- transform: applies a 3D transformation to an element, such as rotateX(), rotateY(), rotateZ(), translateX(), translateY(),translateZ(), scale(), and skew()
- transform-origin: specifies the origin point of the transformation
- backface-visibility: determines whether or not the back face of an element should be visible when the element is rotated.
153 What is color contrast? Hard
Color contrast measures the difference in perceived luminance between foreground text/elements and their underlying background.
### Web Content Accessibility Guidelines (WCAG 2.1) Standards:
- Level AA (Minimum Requirement):
- Normal text (< 18pt or < 14pt bold): Minimum 4.5:1 contrast ratio.
- Large text (≥ 18pt or ≥ 14pt bold): Minimum 3:1 contrast ratio.
- UI components and graphical objects: Minimum 3:1 contrast ratio.
- Level AAA (Enhanced Standard):
- Normal text: Minimum 7:1 contrast ratio.
- Large text: Minimum 4.5:1 contrast ratio.
Meeting color contrast standards ensures that users with low vision, color blindness, or those viewing screens in direct sunlight can read content effortlessly.
154 How does color contrast applies to accessibility in web design? Hard
It is important because people with visual impairments or color blindness may have trouble seeing things if there is not enough contrast. There are guidelines for making sure there is enough contrast which makes the website content more accessible to the people.
155 How do you optimize responsive images for faster loading in CSS? Hard
To optimize responsive images for faster loading in CSS, you can use smaller file formats like JPEG and PNG, reduce the image size and resolution, and use lazy loading to only load images when they are needed.
156 What are mixins in SASS? Hard
A mixin is a feature in Sass that allows you to define a set of CSS styles that can be reused throughout your stylesheet. Example:
@mixin my-text-style {
font-size: 16px;
font-weight: bold;
}
/* we can use the whole style like this now */
h1 {
@include my-text-style;
}
All 156 questions loaded
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.