CSS Interview Questions for Experienced

1. Difference between CSS grid vs flexbox?

Ans: CSS Grid Layout is a two-dimensional layout system that can manage both rows and columns. It is ideal for large-scale layouts that are not strictly linear in design.

Flexbox is a one-dimensional layout system, working in either a row or a column. It is best suited for arranging components within an application.

2. Explain CSS position property?

Ans: The position property in CSS is used to control the layout and positioning of HTML elements on a web page. It defines how an element is positioned in the document flow and how it relates to other elements.

Types of CSS Position Values

  1. static (default)

    • The element is positioned according to the normal document flow.

    • Top, right, bottom, and left properties have no effect.

  2. relative

    • The element remains in the normal flow but can be shifted using top, right, bottom, and left.

    • Its position is relative to itself.

    css
    position: relative;
    top: 10px; /* Moves the element 10px down */
  3. absolute

    • The element is removed from the normal document flow.

    • It is positioned relative to the nearest positioned ancestor (i.e., an ancestor with relative, absolute, or fixed position).

    • If no such ancestor exists, it is positioned relative to the <html> element.

    css
    position: absolute;
    left: 50px;
  4. fixed

    • The element is removed from the normal flow and positioned relative to the browser window.

    • It does not move when the page is scrolled.

    css
    position: fixed;
    bottom: 0;
    right: 0;
  5. sticky

    • The element acts like relative until it reaches a defined scroll position, then behaves like fixed.

    • Often used for sticky headers or menus.

    css
    position: sticky;
    top: 0;

Summary Table

Value Removed from Flow? Positioned Relative To Scrolls with Page?
static No Normal flow Yes
relative No Its normal position Yes
absolute Yes Nearest positioned ancestor No
fixed Yes Viewport No
sticky No Scrolls until fixed at a threshold Partially

3. When does DOM reflow occur?

Ans: Reflow is the process in web browsers where the positions and geometries of elements in the document are recalculated to re-render part or all of the page.

Reflow can occur when you:

  • Insert, remove, or update an element in the DOM

  • Modify content on the page (e.g., change text in an input box)

  • Move a DOM element

  • Animate a DOM element

  • Take measurements of an element (e.g., offsetHeight, getComputedStyle)

  • Change a CSS style

4. Different Box Sizing Property?

Ans: The box-sizing CSS property defines how the total width and height of an element are calculated.

  • Content-box (default): The width and height apply only to the content. Padding and border are added outside the box, increasing the total size.

  • Padding-box: The width and height include the content and padding. The border is added outside. (Note: Supported only in Firefox.)

  • Border-box: The width and height include content, padding, and border. This keeps the total size consistent regardless of padding or border.

5. How to center align a div inside another div?

Ans:

1. Horizontally Center a div (inline-block or block)

Using margin: auto:

html
<div style="width: 300px; background: lightgray;">
<div style="width: 100px; margin: 0 auto; background: tomato;">
Centered
</div>
</div>

 2. Horizontally and Vertically Center Using Flexbox

This is the most modern and widely used method.

html
<div style="display: flex; justify-content: center; align-items: center; height: 200px; background: lightgray;">
<div style="width: 100px; background: tomato;">
Centered
</div>
</div>
  • justify-content: center → centers horizontally

  • align-items: center → centers vertically

 3. Using Grid (Modern Alternative)

html
<div style="display: grid; place-items: center; height: 200px; background: lightgray;">
<div style="width: 100px; background: tomato;">
Centered
</div>
</div>

4. Absolute Positioning (Older Method)

html
<div style="position: relative; height: 200px; background: lightgray;">
<div style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); background: tomato;">
Centered
</div>
</div>

6. Can you name the four types of @media properties?

Ans: The four types of @media properties are:

  1. All – Default media type. Applies to all devices.

  2. Screen – Targets screens such as desktops, laptops, tablets, and mobiles.

  3. Print – Designed for printed material or print preview mode.

  4. Speech – Used for screen readers that read the content aloud.

7. What is the grid system?

Ans: CSS Grid Layout is a powerful layout system in CSS. It is a two-dimensional system that allows the design of layouts in both rows and columns, unlike Flexbox, which primarily handles layout in a single dimension — either a row or a column.

8. What are the different ways to hide the element using CSS?

Ans: Using the display property (display: none)
The element will not be visible and will not occupy space on the page. It is also not available to screen readers. The element effectively does not exist in the DOM for both visual and assistive technologies.

Using the visibility property (visibility: hidden)
The element will not be visible, but it will still occupy space on the page. It remains available to screen readers, and the element exists in the DOM but is hidden from view.

Using the position property (position: absolute)
You can move the element off-screen using this property (e.g., by setting a large negative left or top value). This makes the element invisible to users, but it remains in the DOM and accessible to screen readers.

9. What does the :root pseudo-class refer to?

Ans: The :root selector is used to target the highest-level element in the DOM, typically the <html> element. It is defined in the CSS Selectors Level 3 specification.

10. What does Accessibility (a11y) mean?

Ans: Accessibility refers to the design of software and hardware systems that enable access for individuals with disabilities, such as visual impairments, hearing loss, or limited mobility.

For example, an accessible website might include features like text-to-speech support or keyboard navigation. In the United States, public websites are required to comply with accessibility standards defined under Section 508. This regulation outlines key guidelines and best practices to ensure websites are usable by all individuals, regardless of their abilities.

11. How does Calc work?

Ans: The CSS3 calc() function allows us to perform mathematical operations on property values. Instead of assigning static values (like pixels) to a CSS property, we can use calc() to dynamically compute values using addition, subtraction, multiplication, or division.

Example:

css
.foo {
width: calc(100px + 50px);
}

In this example, the element with class .foo will have a width of 150px.

12. How do I restore the default value of a property?

Ans: The initial keyword in CSS can be used to reset a property to its default value as defined by the CSS specification.

13. What do CSS Custom properties variables mean?

Ans: Custom properties, also known as CSS variables, allow users to define reusable values throughout a stylesheet. They are declared using the -- prefix and accessed with the var() function.

Corrected CSS Code:

css
:root {
--main-bg-color: brown;
}
.one {
color: white;
background-color: var(–main-bg-color);
margin: 10px;
width: 50px;
height: 50px;
display: inline-block;
}
Corrections Made:
  • Fixed typo background-color· to background-color:

  • Removed space in var (--main-bg-color) to var(--main-bg-color)

  • Fixed margin: l0px, to margin: 10px; (used lowercase L instead of 1)

  • Replaced commas , with semicolons ; at the end of CSS declarations

  • Corrected height: 5Opx; to height: 50px; (used capital “O” instead of zero)

14. What does * { box-sizing: border-box; } do? What are its advantages?

Ans: The CSS rule * { box-sizing: border-box; } applies the box-sizing: border-box property to all elements on the page.

What box-sizing: border-box Does:

By default, elements use box-sizing: content-box, which means:

  • The width and height apply only to the content.

  • Padding and border are added outside the specified width/height.

With box-sizing: border-box, this changes:

  • The width and height include content, padding, and border.

  • So, if you set width: 200px, the total space it takes up stays 200px, even if you add padding or a border.

Advantages of box-sizing: border-box:

  1. Predictable Layouts:

    • It makes layouts easier to manage because padding/border don’t expand the element’s size.

  2. Simpler Math:

    • No need to manually subtract padding/border from the width/height.

  3. Consistent Design:

    • Keeps element sizes consistent, which helps avoid overflow and layout bugs.

  4. Better for Responsive Design:

    • Easier to control element sizes on different screen sizes.

Common Usage:

It’s widely used in modern CSS resets and frameworks like this:

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

This ensures even pseudo-elements follow the same box-sizing behavior.

15. What is the difference between CSS variables and preprocessor(SASS, LESS, Stylus) variables?

Ans:  CSS variables can be used directly in modern browsers without the need for a preprocessor, as all major browsers currently support them. Unlike preprocessor variables, CSS variables follow the cascade, allowing inheritance and dynamic behavior. Additionally, CSS variables can be accessed and manipulated using JavaScript.

16. What does !important mean in CSS?

Ans:  The style rule with !important has the highest precedence and overrides other conflicting rules, even those with higher specificity.

css
p {
color: red !important;
}
#thing {
color: green;
}
html
<p id="thing">Will be RED.</p>

Explanation:
Although the #thing selector is more specific, the color: red !important; in the p selector overrides it, so the paragraph text will appear red.

17. What is progressive rendering? How do you implement progressive rendering in the website?. What are the advantages of it?

Ans:  Progressive Rendering is a web development technique used to improve perceived performance by displaying parts of a web page as soon as they’re ready, instead of waiting for all resources to load. This approach enhances user experience, especially on slower networks or content-heavy websites.

What is Progressive Rendering?

Progressive rendering refers to strategies that render and display content incrementally rather than all at once. This can include:

  • Showing basic structure first (HTML/CSS)

  • Lazy-loading images or scripts

  • Streaming content to the browser in chunks

How to Implement Progressive Rendering

Here are some common ways to implement it:

1. Server-Side Rendering with Chunked Transfer Encoding

  • Sends HTML to the browser in parts.

  • The browser starts parsing and rendering before the entire page is received.

js
// In Node.js with Express (simplified)
res.write('<html><head><title>Title</title></head><body>');
res.write('<div>Loading content...</div>');
res.flush(); // Sends this part immediately
// Later
res.write('<div>More content here</div>');
res.end('</body></html>');

2. Lazy Loading

  • Delay loading of non-critical resources, like images, videos, or below-the-fold content.

html
<img src="image.jpg" loading="lazy" alt="..." />

3. Skeleton Screens or Content Placeholders

  • Show grey blocks or loading animations while the real content is fetched.

html
<div class="skeleton-loader">Loading...</div>

4. Code Splitting

  • Divide your JavaScript code into smaller bundles that load as needed.

js
// In React using dynamic import
const LazyComponent = React.lazy(() => import('./Component'));

5. Prioritize Above-the-Fold Content

  • Ensure CSS and content for the top portion of the page is loaded and rendered first.

Use <link rel="preload">, inlined CSS, or move blocking scripts to the bottom of the page.

Advantages of Progressive Rendering

Benefit Description
⚡ Faster Perceived Load Users see content sooner, improving UX
📶 Better on Slow Networks Prioritizes essential content
🧠 Perception of Performance Gives a feeling of responsiveness
📱 Mobile-Friendly Optimizes experience on low-power devices
💡 Incremental Loading Reduces Time to First Byte (TTFB) & First Contentful Paint (FCP)

18. What is specificity? How to calculate specificity?

Ans:  CSS Specificity:
     It is the process of determining which CSS rule will be applied to an element when multiple rules target the same element. Specificity defines the priority of each rule. Inline styles have the highest specificity, followed by ID selectors, then class selectors (including pseudo-classes and attribute selectors). The universal selector (*) has the lowest specificity. ID selectors have higher specificity than class or attribute selectors.

19. What are the advantages of using translate() instead of absolute position?

Ans: translate() does not trigger a browser repaint or layout recalculation; it operates solely on the compositor layer. In contrast, using absolute positioning can cause a repaint or DOM reflow. Therefore, translate() offers better performance.

20. Does style1.css have to be downloaded and parsed before style2.css can be fetched?

Ans: <head>
<link href=”style1.css” rel=”stylesheet”>
<link href=”style2.css” rel=”stylesheet”>
</head>
Explanation:
No, the browsers will download and apply the CSS files in the order they appear in the HTML page. If both files contain styles for the same elements, the second file (style2.css) will override the styles defined in the first (style1.css) due to the CSS cascade.

21. How to determine if the browser supports a certain feature?

Ans: The @supports rule in CSS is useful for checking whether the current browser supports a specific CSS feature.

css
@supports (display: grid) {
div {
display: grid;
}
}

If the browser supports display: grid, the styles inside the block will be applied. This helps in writing fallback-friendly and progressive CSS.

22. How will you fix browser-specific styling issues?

Ans: To fix browser-specific styling issues, you can follow these approaches:

  1. Use CSS Resets or Normalize.css:
    Apply a CSS reset or use normalize.css to create consistent default styling across browsers.

  2. Vendor Prefixes:
    Add browser-specific prefixes (e.g., -webkit-, -moz-, -ms-, -o-) to ensure support for experimental or non-standard CSS properties.

  3. Feature Detection with Modernizr:
    Use libraries like Modernizr to detect features and apply styles or scripts conditionally.

  4. Conditional Comments (for older IE versions):
    Use conditional comments in HTML to target specific versions of Internet Explorer.

  5. Targeting with Hacks (last resort):
    Apply CSS hacks only when absolutely necessary, as they reduce maintainability. Prefer using proper techniques first.

  6. Cross-Browser Testing Tools:
    Use tools like BrowserStack or CrossBrowserTesting to test your site across different browsers and devices.

  7. Use Standard and Valid Code:
    Write valid, standards-compliant HTML/CSS to minimize issues across browsers.

23. How does this property work overflow: hidden?

Ans: How overflow: hidden Works:

When applied, it hides any content that goes beyond the dimensions (width/height) of the element. That means:

  • Extra content is not visible

  • No scrollbars appear

  • The overflowing parts are simply clipped

 Syntax:

css
selector {
overflow: hidden;
}

Example:

html
<div style="width: 200px; height: 100px; overflow: hidden; border: 1px solid #000;">
<p>This is a very long paragraph that will overflow the div container and get clipped when overflow is set to hidden.</p>
</div>

In this example:

  • The paragraph is taller than the div.

  • Because of overflow: hidden, the extra text that doesn’t fit within the 100px height will be cut off and not shown.

Common Use Cases:

  • Creating clean layouts without scrollbars.

  • Hiding scrollable content temporarily.

  • Clearing floats in layout techniques (often with overflow: hidden on the parent element).

If you want to see the content (by scrolling), you would use overflow: auto or overflow: scroll instead.

24. How will you align content inside the p tag at the exact center inside the div?

Ans: We can align content horizontally by using the text-align: center property inside the parent div. However, this does not align the content vertically.

To center content both horizontally and vertically, we can use the following approach:

  1. Set the parent element’s position to relative.

  2. Set the child element’s position to absolute.

  3. Use top, bottom, left, and right as 0 on the child element.

  4. Set margin: auto on the child to center it within the parent.

  5. Ensure both parent and child elements have defined height and width.

Example:

Suppose we have a div that takes up 20% of the screen’s height and width, and inside it a p tag with a height of 1.2em and width of 20%. Here’s how we can center the paragraph inside the div:

css
div {
position: relative; /* Make parent relative */
height: 20vh;
width: 20vw;
text-align: center; /* Center horizontally */
}
p {
position: absolute; /* Make child absolute */
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto; /* Auto margin centers the element */
height: 1.2em;
width: 20%;
}

25. How is margin different from padding in CSS?

Ans: In CSS, margin and padding are both used for spacing, but they serve different purposes and apply to different areas of an element:

Padding

  • What it is: Space inside the element, between the content and the border.

  • Purpose: Creates breathing room within an element.

  • Affects background: Yes, padding is part of the element’s background area.

Example:

css
.box {
padding: 20px;
}

This adds 20px of space inside the box, between the content and its border.

Margin

  • What it is: Space outside the element, between the border and the next element.

  • Purpose: Creates space between elements.

  • Affects background: No, margins are outside the element and not filled with background color.

Example:

css
.box {
margin: 20px;
}

This adds 20px of space outside the box, pushing other elements away from it.

Key Difference Table

Feature Margin Padding
Location Outside the element Inside the element
Affects layout Pushes elements apart Increases element size
Affects background No Yes
Collapses? Margins can collapse Padding never collapses

26. What do you have to do to automatically number the heading values of sections and categories?

Ans: To automatically number the heading values of sections and categories in a document (like in HTML, Word, or LaTeX), the steps depend on the platform or tool you’re using. Here’s how you can do it in a few common environments:

1. Microsoft Word:

To auto-number headings:

  • Apply built-in heading styles (Heading 1, Heading 2, etc.) to your headings.

  • Then go to:

    • Home tab → Multilevel List → Choose a numbering format that links to the heading styles (e.g., 1, 1.1, 1.1.1).

This will create automatic hierarchical numbering like:

css
1. Section Title
1.1 Subsection
1.2 Subsection
2. New Section

2. HTML + CSS (with JavaScript or CSS Counters):

In HTML/CSS, you can use CSS counters to auto-number headings.

Example:

html
<style>
body {
counter-reset: section;
}
h2 {
counter-increment: section;
}
h2::before {
content: counter(section) ". ";
}
</style>
<h2>Introduction</h2>
<h2>Methodology</h2>
<h2>Conclusion</h2>

Output:

markdown
1. Introduction
2. Methodology
3. Conclusion

3. LaTeX:

In LaTeX, section and subsection numbering is automatic:

latex
\section{Introduction}
\subsection{Background}
\subsection{Objectives}
\section{Method}

Output:

mathematica
1 Introduction
1.1 Background
1.2 Objectives
2 Method

4. Markdown (with Pandoc or Extensions):

Markdown doesn’t support numbering natively, but tools like Pandoc can do it:

Command:

bash
pandoc --number-sections input.md -o output.pdf

Summary:

Platform Method
Word Use heading styles + multilevel list
HTML/CSS Use CSS counters
LaTeX Built-in automatic section numbering
Markdown (Pandoc) Use --number-sections flag

27. How is the nth-child() different from nth of type selectors?

Ans: The :nth-child() and :nth-of-type() CSS pseudo-classes are both used to select elements based on their position within a parent, but they differ in what elements they count and how they match:

:nth-child(n)

  • Matches based on position among all children of a parent, regardless of type.

  • It selects the element if it is the nth child of any type (element node).

Example:

html
<ul>
<li>Item 1</li>
<p>Paragraph</p>
<li>Item 2</li>
</ul>
li:nth-child(3) {
color: red;
}

Here, the li:nth-child(3) won’t match anything because the third child is a <li>, but it’s the third overall child, not the third <li>.

:nth-of-type(n)

  • Matches based on position among siblings of the same type (same tag name).

  • It selects the nth element of its type among its siblings.

Example:

html
<ul>
<li>Item 1</li>
<p>Paragraph</p>
<li>Item 2</li>
</ul>
li:nth-of-type(2) {
color: red;
}

This will select the second <li>, even though it’s the third child overall.

Key Difference:

Selector Counts Matches if…
:nth-child(n) All element siblings It is the nth overall child of its parent
:nth-of-type(n) Same-tag siblings It is the nth child of the same tag type among siblings

28. What is the importance of CSS Sprites?

Ans: CSS Sprites are a technique in web development where multiple images are combined into a single image file. Instead of loading many separate images, a single sprite sheet is loaded, and CSS is used to display only the relevant portion of that image.

Importance of CSS Sprites

  1. Reduces HTTP Requests:

    • Loading each image separately requires a new HTTP request. CSS Sprites combine images into one file, reducing the number of requests and improving page load time.

  2. Improves Performance:

    • Fewer HTTP requests mean faster loading, especially for image-heavy websites, leading to better performance and user experience.

  3. Efficient Bandwidth Usage:

    • Since only one image is downloaded, the overall bandwidth consumption is reduced, which is beneficial for both users and servers.

  4. Better Caching:

    • A single sprite image can be cached by the browser. This means the image is loaded only once, and reused on subsequent visits, speeding up the site.

  5. Organized Image Management:

    • Developers can manage multiple small icons or graphics in a centralized image file, making updates and maintenance easier.

  6. Enhances SEO & Accessibility (indirectly):

    • Faster page loads can lead to improved SEO rankings and better accessibility for users on slow connections or mobile devices.

Use Case Examples:

  • Navigation icons

  • Social media buttons

  • Thumbnail images

  • UI elements like buttons, arrows, stars, etc.

While CSS Sprites are still useful, modern alternatives like SVGs, icon fonts, and image optimization tools (combined with HTTP/2 benefits) are now often preferred depending on the project needs.

29. What do you understand by tweening in CSS?

Ans: Tweening in CSS (short for “in-betweening”) refers to the process of creating intermediate steps or transitions between two states of an element — such as from one position, color, size, or opacity to another — to create smooth animations.

Explanation:

Tweening is not a built-in CSS term, but it’s a concept borrowed from animation. In CSS, it’s usually implemented using:

  1. CSS Transitions – for smooth changes from one state to another when triggered by an event (like hover or click).

  2. CSS Animations – for more complex or keyframe-based animations that play automatically or based on a class change.

Example using CSS Transitions:

css
.box {
width: 100px;
height: 100px;
background: red;
transition: background 0.5s ease, transform 0.5s ease;
}
.box:hover {
background: blue;
transform: scale(1.2);
}

When you hover over the .box, it tweens smoothly from red to blue and scales up.

Example using CSS Animations (Keyframe Tweening):

css
@keyframes slide {
0% { transform: translateX(0); }
100% { transform: translateX(200px); }
}
.box {
animation: slide 1s ease-in-out forwards;
}

This creates tweening between the initial and final translateX values.

30. Why do we need to use clear property along with floats in CSS?

Ans: In CSS, the clear property is used in combination with floats to control the behavior of elements after a floated element. Here’s why and when we need it:

Why we need the clear property with floats:

When you float an element (float: left or float: right), it is taken out of the normal document flow. This means that:

  • Non-floated elements that come after it can wrap around the floated element instead of appearing below it.

  • The parent container may collapse in height, because it no longer “sees” the floated children.

What the clear property does:

The clear property prevents an element from appearing next to (or wrapping around) a floated element. It forces the element to move below the floated elements.

Common use cases:

To stop text or elements from wrapping around floats:

html
<img src="image.jpg" style="float: left;">
<p>This paragraph will wrap around the floated image unless we use clear.</p>
<p style="clear: both;">This paragraph will start below the floated image.</p>

To fix collapsing parent containers:

Use a clearing element (or clearfix technique) to force the parent to recognize the floated children.

css
.clearfix::after {
content: "";
display: table;
clear: both;
}
html
<div class="clearfix">
<div style="float: left;">Floated</div>
</div>

Values of clear:

  • left: Clear floats on the left side

  • right: Clear floats on the right side

  • both: Clear both sides

  • none: Default; does not clear

You use the clear property to:

  • Prevent overlap/wrapping caused by floated elements.

  • Restore normal layout flow after floating.

  • Ensure layout consistency when using floats in complex designs.

31. How does the absolute positioning work?

Ans:  Absolute Positioning in CSS

Absolute positioning is a powerful CSS technique that allows you to place an element at a precise location on the page. You can define the element’s position using the top, right, bottom, and left properties. When using absolute positioning, consider the following points:

  • The element is removed from the normal document flow, meaning it does not occupy space in the layout.

  • Other elements will behave as if the absolutely positioned element does not exist.

  • The element is positioned relative to the nearest positioned ancestor (an ancestor with a position value other than static).

  • If no such ancestor is found, the element is positioned relative to the initial containing block (usually the <html> element or browser window).

  • The final position of the element is determined by the values specified for top, right, bottom, and left.