CSS Interview Questions For Freshers

1. What are the advantages of using CSS?

Ans: The main advantages of CSS are given below:

  1. Separation of Content from Presentation
    CSS allows content to be separated from its presentation, enabling the same content to be displayed in different formats across devices such as mobile, desktop, or laptop.

  2. Easy Maintenance
    When CSS is structured efficiently, small changes can update the look and feel of an entire website. By modifying a single style rule, all associated elements across all web pages get updated automatically.

  3. Improved Bandwidth Usage
    CSS files, when used properly, are cached by the browser and reused across multiple pages. This reduces the need to download the same style sheets repeatedly, improving load time and saving bandwidth.

2. How do you specify units in the CSS?. What are the different ways to do it?

Ans: There are various ways to specify units in CSS, such as px, em, pt, and % (percentage):

  • px (Pixels): Offers fine-grained control and ensures sharp alignment, as 1px or its multiples render precisely. However, px is not relative and does not cascade with parent elements.

  • em: A relative unit that scales based on the current font size of the element or its parent. 1em equals the font size of the element it is applied to. If the root font size is set to 16px, then 1em = 16px. Cascading can occur, which allows for responsive typography. A common practice is setting the body font-size to 62.5% (equal to 10px), making it easier to calculate sizes with em.

  • pt (Points): Primarily used in print media. 1pt = 1/72 inch. It is a fixed-size unit and not ideal for screen displays.

  • % (Percentage): Sets the font size relative to the font size of the parent element (commonly the body). To use percentages effectively, it’s important to define a reasonable body font-size first.

3. What is the Box model in CSS? Which CSS properties are a part of it?

Ans: The CSS Box Model is a fundamental concept in web design and layout. It describes how every HTML element is essentially a rectangular box, and how the space around it is calculated and rendered.

Components of the Box Model:

Each box consists of the following (from inside out):

  1. Content

    • The actual content of the box (text, image, etc.).

    • Affected by: width, height.

  2. Padding

    • Space between the content and the border.

    • Affected by: padding (can be padding-top, padding-right, padding-bottom, padding-left).

  3. Border

    • The edge of the box, surrounding the padding (if any).

    • Affected by: border (like border-width, border-style, border-color).

  4. Margin

    • Space outside the border, separating the element from other elements.

    • Affected by: margin (can be margin-top, margin-right, margin-bottom, margin-left).

CSS Properties in the Box Model:

Box Model Part CSS Properties
Content width, height, min-width, max-width, min-height, max-height
Padding padding, padding-top, padding-right, padding-bottom, padding-left
Border border, border-width, border-style, border-color, border-radius
Margin margin, margin-top, margin-right, margin-bottom, margin-left

4. What are the limitations of CSS?

Ans: Disadvantages of CSS are given below:

  1. Browser Compatibility: Some CSS selectors are supported in certain browsers but not in others. Developers often need to check compatibility using the @supports rule.

  2. Cross-Browser Issues: Certain selectors or properties may behave differently across various browsers, which can lead to inconsistent designs.

  3. No Parent Selector: CSS does not currently support selecting a parent element based on a child, limiting some styling possibilities.

5. How to include CSS in the webpage?

Ans: There are different ways to include CSS in a webpage:

1. External Style Sheet
An external file linked to your HTML document. Use the <link> tag to connect the stylesheet to the HTML page.

html
<link rel="stylesheet" type="text/css" href="mystyles.css" />

2. Embedded CSS (Using <style> tag)
A set of CSS rules included within your HTML page using the <style> tag, placed inside the <head> section.

html
<style type="text/css">
/* Add style rules here */
</style>

Write your CSS rules between the opening and closing <style> tags, just as you would in a standalone CSS file.

3. Inline CSS
CSS rules applied directly within an HTML element using the style attribute.

html
<h2 style="color: red; background: black;">Inline Style</h2>

4. Imported Style Sheet
An external CSS file imported into another CSS file using the @import rule.

css
@import "path/to/style.css";

This method is typically used within a CSS file to include additional styles from another stylesheet.

6. What are the different types of Selectors in CSS?

Ans: In CSS, selectors are patterns used to select and style HTML elements. There are several types of selectors, each serving a specific purpose. Here’s a breakdown of the most common types:

1. Universal Selector

  • Syntax: *

  • Description: Selects all elements on the page.

  • Example:

    css
    * {
    margin: 0;
    padding: 0;
    }

2. Type (Element) Selector

  • Syntax: elementName

  • Description: Selects all elements of a specific type.

  • Example:

    css
    p {
    font-size: 16px;
    }

3. Class Selector

  • Syntax: .className

  • Description: Selects all elements with the specified class.

  • Example:

    css
    .highlight {
    background-color: yellow;
    }

4. ID Selector

  • Syntax: #idName

  • Description: Selects an element with the specific ID (must be unique).

  • Example:

    css
    #header {
    color: blue;
    }

5. Group Selector

  • Syntax: selector1, selector2, ...

  • Description: Groups multiple selectors to apply the same styles.

  • Example:

    css
    h1, h2, h3 {
    font-family: Arial;
    }

6. Descendant Selector

  • Syntax: ancestor descendant

  • Description: Selects all elements that are descendants of a specified element.

  • Example:

    css
    div p {
    color: green;
    }

7. Child Selector

  • Syntax: parent > child

  • Description: Selects direct child elements only.

  • Example:

    css
    ul > li {
    list-style: none;
    }

8. Adjacent Sibling Selector

  • Syntax: element1 + element2

  • Description: Selects the first element2 immediately after element1.

  • Example:

    css
    h1 + p {
    font-style: italic;
    }

9. General Sibling Selector

  • Syntax: element1 ~ element2

  • Description: Selects all element2 siblings after element1.

  • Example:

    css
    h1 ~ p {
    color: gray;
    }

10. Attribute Selector

  • Syntax: element[attribute=value]

  • Description: Selects elements with specific attributes.

  • Example:

    css
    input[type="text"] {
    border: 1px solid #ccc;
    }

11. Pseudo-class Selector

  • Syntax: selector:pseudo-class

  • Description: Targets elements based on state or position.

  • Examples:

    css
    a:hover {
    color: red;
    }
    li:first-child {
    font-weight: bold;
    }

12. Pseudo-element Selector

  • Syntax: selector::pseudo-element

  • Description: Styles parts of elements.

Examples:

  • css
  • p::first-line {
    font-size: 18px;
    }
  • p::before {
    content: “Note: “;
    color: red;
    }

7. What is a CSS Preprocessor? What are Sass, Less, and Stylus? Why do people use them?

Ans: A CSS Preprocessor is a scripting language that extends CSS and gets compiled into standard CSS code. It allows developers to use features that aren’t available in pure CSS—such as variables, nesting, mixins, functions, and more—making stylesheets more powerful and easier to maintain.

What is a CSS Preprocessor?

A CSS Preprocessor works before CSS is sent to the browser. You write styles in a preprocessor language, and then compile it into regular CSS.

Benefits:

  • Better code organization

  • Reuse via variables and mixins

  • Easier maintenance

  • Cleaner syntax with nesting

  • Use of functions and conditionals

Popular CSS Preprocessors

1. Sass (Syntactically Awesome Stylesheets)

  • Most widely used.

  • Two syntaxes:

    • .scss (CSS-like syntax)

    • .sass (indented syntax without braces/semicolons)

  • Powerful features: variables, nesting, mixins, inheritance, functions, control directives.

2. Less (Leaner Style Sheets)

  • Similar to Sass, but uses JavaScript for processing.

  • Syntax is closer to CSS.

  • Common in older frontend frameworks (e.g., Bootstrap v3).

3. Stylus

  • Very flexible and concise.

  • Optional semicolons, colons, and braces.

  • Allows very minimalist syntax.

Why Use CSS Preprocessors?

Feature Benefit
Variables Store colors, fonts, dimensions
Nesting Organize selectors hierarchically
Mixins Reusable blocks of styles
Inheritance Share styles across selectors
Functions Perform calculations or manipulate colors
Modularity Split CSS into multiple files

8. What is VH/VW (viewport height/ viewport width) in CSS?

Ans: VH and VW Units in CSS:

VH (viewport height) and VW (viewport width) are CSS units used to measure dimensions relative to the viewport. These units are especially useful in responsive design.

  • 1vh equals 1% of the viewport height. For example, if the browser height is 1000px, then 1vh = 10px.

  • 1vw equals 1% of the viewport width. If the browser width is 1000px, then 1vw = 10px.

These units help ensure layouts adjust dynamically across different screen sizes.

9. Difference between reset vs normalize CSS?. How do they differ?

Ans: Reset CSS:
Reset CSS removes all default browser styling, such as margins, paddings, and font sizes, by setting them to a consistent baseline for all elements.

Normalize CSS:
Normalize CSS preserves useful default styles while making them consistent across browsers. It also fixes common browser inconsistencies and bugs.

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

Ans: Block Elements:
Block elements always start on a new line and occupy the full width available (the entire row). Common examples include <div> and <p>.

Inline Elements:
Inline elements do not start on a new line and appear alongside other content and tags. Examples include <a>, <span>, <strong>, and <img>.

Inline-Block Elements:
Inline-block elements behave like inline elements in that they appear on the same line, but they can also accept padding, margins, height, and width values like block elements.

11. Is it important to test the webpage in different browsers?

Ans: It is crucial to test a website in different browsers during the initial design phase or when implementing major updates. Additionally, periodic testing is important, as browsers frequently receive updates and changes that may affect website performance or appearance.

12. What are Pseudo elements and Pseudo classes?

Ans: Pseudo-elements allow us to style parts of an element or create elements that don’t exist in the HTML structure. Common pseudo-elements include:

ruby
::before
::after
::first-letter
::first-line
::selection

For example, the following CSS applies styles only to the first line of a paragraph:

css
p::first-line {
color: #FF0000;
font-variant: small-caps;
}

Pseudo-classes are used to define a special state of an element — for instance, when a user hovers over a link. Common pseudo-classes include:

css
:link
:visited
:hover
:active
:focus

Here is an example using the :hover pseudo-class to change the color of a link when the mouse is over it:

css
a:hover {
color: #FF00FF;
}

13. Does margin-top or margin-bottom have an effect on inline elements?

Ans: No, it doesn’t affect inline elements, as they flow naturally with the content of the page.

14. What is cascading in CSS?

Ans: Cascading is the process by which the browser resolves conflicts between multiple CSS rules that target the same element. When two or more declarations apply to an element, the browser “cascades” through them—considering origin (author, user, or user‑agent), specificity, and source order—to decide which rule wins.

For example, imagine these two rules:

css
/* Rule A */
p {
color: white;
}

/* Rule B, later in the stylesheet or in another linked file */
p {
color: black;
}

Both rules apply to <p> elements, so the browser uses the one with higher specificity or, if specificity is equal, the one defined last. Here, Rule B wins, so paragraphs render in black.

If you really want white text, you can boost the priority of Rule A by using !important:

css
p {
color: white !important;
}

An !important declaration overrides all other declarations for that property on that element, regardless of origin or order.

15. What property is used for changing the font face?

Ans: We can achieve this using the font-family property, which specifies the font to be applied to the targeted DOM element. This property can contain multiple font names to serve as a fallback mechanism in case the browser does not support a particular font.

For example:

css
p {
font-family: "Times New Roman", Times, serif;
}

In the code above, the font-family property is applied to the paragraph (<p>) element. It instructs the browser to:

  1. Use the “Times New Roman” font if available.

  2. If not, fall back to the Times font.

  3. If neither font is available, use any supported serif font as a generic fallback.

If you prefer the paragraph to use Arial, with fallbacks to Helvetica and then a generic sans-serif font, you can update the CSS as shown below:

css
p {
font-family: Arial, Helvetica, sans-serif;
}

16. What are the differences between adaptive design and responsive design?

Ans:

Adaptive Design Responsive Design
Adaptive design focuses on creating websites with multiple fixed layout sizes tailored to specific screen widths. Responsive design focuses on displaying content dynamically based on the available browser space.
When a website built with adaptive design is accessed on a desktop browser, the available screen size is first detected, and then the most suitable layout is selected. Resizing the browser window does not affect the layout. When a website built with responsive design is accessed and the browser window is resized, the content automatically adjusts and rearranges to fit the screen optimally.
Typically, adaptive design uses six standard screen widths: 320 px, 480 px, 760 px, 960 px, 1200 px, and 1600 px. The layout is chosen based on these predefined sizes. Responsive design relies on CSS media queries to change styles according to the properties of the target device, enabling it to adapt to various screen sizes.
Designing adaptive layouts requires more time and effort, as it involves analyzing the users’ devices and creating suitable layouts for each. Responsive design generally requires less effort, as it involves building flexible layouts that adjust fluidly based on screen size.
Offers more control over the design, allowing developers to target specific devices and screen sizes precisely. Offers less granular control over specific layouts, as it prioritizes flexibility and fluidity across all screen sizes.

17. How are the CSS selectors matched against the elements by the browser?

Ans: CSS selectors are matched against HTML elements by the browser using a process called selector matching, which is part of the CSS rendering engine. Here’s a breakdown of how this matching process works:

1. Selector Parsing

The browser first parses all CSS rules, breaking them into individual selectors and declarations (property-value pairs).

 2. Right-to-Left Matching

Browsers match selectors right-to-left (from the most specific part to the least specific). This means:

css
div.container ul li.active
  • The browser first looks for all <li> elements with class active.

  • Then checks if they are inside a <ul>, which is inside a <div> with class container.

 This strategy is more efficient because it’s faster to find specific elements first than to walk through every element in the DOM.

 3. DOM Traversal

Once the browser identifies a candidate element (starting from the rightmost selector), it traverses up the DOM to check if the ancestor elements match the remaining parts of the selector.

4. Specificity Calculation

If multiple selectors match the same element, the browser uses specificity rules to determine which styles to apply:

  • Inline styles > IDs > Classes/Attributes > Elements

  • More specific selectors override less specific ones.

5. Cascade and Inheritance

After matching and specificity, the browser resolves conflicts using the cascade, and some properties may be inherited (e.g., color, font-family).

Example:

Given this HTML:

html
<div class="wrapper">
<ul>
<li class="active">Item</li>
</ul>
</div>

And CSS:

css
div.wrapper ul li.active {
color: red;
}

Matching steps:

  1. Start with li.active → find <li class="active">

  2. Check parent is <ul>

  3. Check grandparent is <div class="wrapper">

  4. If all match → apply the style

18. How is border-box different from content-box?

Ans: In CSS, the difference between border-box and content-box lies in how the total width and height of an element are calculated.

content-box (default value)

  • Only the content’s size is considered for width and height.

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

 Example:

css
width: 200px;
box-sizing: content-box;
  • Actual total width = 200px (content) + padding + border

border-box

  • Content, padding, and border are all included within the specified width and height.

  • This makes it easier to manage layouts.

 Example:

css
width: 200px;
box-sizing: border-box;
  • Actual total width = 200px (includes content + padding + border)


Summary Table:

Property content-box border-box
Width includes Only content Content + padding + border
Total width Width + padding + border Exactly as specified in width
Use case Default behavior, more manual Easier layout control and consistency

Most modern CSS frameworks (like Tailwind and Bootstrap) set box-sizing: border-box globally for simplicity.

19. How is opacity specified in CSS3?

Ans: In CSS3, opacity is specified using the opacity property. This property sets the transparency level of an element, including its content and background.

Syntax:

css
selector {
opacity: value;
}

Value:

  • A number between 0.0 (completely transparent) and 1.0 (completely opaque).

Example:

css
div {
opacity: 0.5; /* 50% transparent */
}

Note:

  • opacity affects the entire element, including all its child elements.

  • If you want to set only the background transparency without affecting text or children, use rgba color instead:

css
div {
background-color: rgba(255, 0, 0, 0.5); /* Red background with 50% opacity */
}

20. Why should we use float property in CSS?

Ans: The float property is used to position HTML elements horizontally, either to the left or right within their container. For example:

css
.float-demo {
float: right;
}

In this example, the element with the class float-demo will be positioned on the right side of its container. Similarly, if you use float: left;, the element will be positioned on the left side of the container.

21. What is a z-index, how does it function?

Ans: The z-index is a CSS property that controls the stacking order of overlapping HTML elements along the z-axis (which is perpendicular to the screen, i.e., “in and out” of the page).

How Does It Function?

  • The higher the z-index value, the closer the element appears to the viewer.

  • Elements with lower z-index values are behind those with higher values.

  • It only works on positioned elements, i.e., elements with position: relative, absolute, fixed, or sticky.

Example:

html
<div style="position: absolute; z-index: 1; background: red; width: 100px; height: 100px;">Box 1</div>
<div style="position: absolute; z-index: 2; background: blue; width: 100px; height: 100px; top: 20px; left: 20px;">Box 2</div>

In this example:

  • Box 2 (z-index: 2) will appear above Box 1 (z-index: 1), even if they overlap.

Key Points:

  • Default z-index is auto, which places elements in the order they appear in the HTML.

  • z-index values can be positive or negative.

  • Nesting matters: A child’s z-index is constrained within the stacking context created by its parent.

Stacking Context

A new stacking context is created when:

  • z-index is set on a positioned element.

  • Certain CSS properties are used (transform, opacity < 1, filter, etc.).

Once a stacking context is created, elements inside it are stacked independently of the outside elements.

22. What do the following CSS selectors mean?

Ans: 1. Element Selector (p)

css
p {
color: blue;
}

Meaning: Selects all <p> (paragraph) elements and applies the styles.

2. Class Selector (.myClass)

css
.myClass {
font-size: 18px;
}

Meaning: Selects all elements with class name myClass.

3. ID Selector (#header)

css
#header {
background: gray;
}

Meaning: Selects the element with ID header. IDs are unique and should be used only once per page.

4. Universal Selector (*)

css
* {
margin: 0;
padding: 0;
}

Meaning: Selects all elements on the page.

5. Descendant Selector (div p)

css
div p {
color: red;
}

Meaning: Selects all <p> elements that are inside a <div> (at any nesting level).

6. Child Selector (ul > li)

css
ul > li {
list-style: none;
}

Meaning: Selects all <li> elements that are direct children of a <ul>.

7. Adjacent Sibling Selector (h2 + p)

css
h2 + p {
margin-top: 0;
}

Meaning: Selects the first <p> element immediately after any <h2>.

8. Attribute Selector (input[type="text"])

css
input[type="text"] {
border: 1px solid #ccc;
}

Meaning: Selects <input> elements with type="text".

23. What are the properties of flexbox?

Ans: Flexbox in CSS

Flexbox stands for Flexible Box Layout. It was introduced around 2017 in CSS to provide an efficient way to design layout structures, align elements, and distribute space within a container—even when the size of the items is unknown or dynamic. Flexbox enhances the flexibility of layout items, allowing them to grow, shrink, or adjust based on the available space.

To enable Flexbox behavior, CSS3 introduced a set of properties, outlined below:

Flexbox Properties:

1. flex-direction

Defines the direction in which flex items are placed in the container. Possible values include:

  • row: (default) Items are placed horizontally, from left to right.

  • row-reverse: Items are placed horizontally, from right to left.

  • column: Items are placed vertically, from top to bottom.

  • column-reverse: Items are placed vertically, from bottom to top.

2. flex-wrap

Specifies whether flex items should wrap or not when there’s not enough space.

  • nowrap: (default) All items are kept on a single line.

  • wrap: Items will wrap onto multiple lines if necessary.

  • wrap-reverse: Items wrap onto multiple lines, but in reverse order.

3. flex-flow

A shorthand property for setting both flex-direction and flex-wrap in one line.
Example:

css
flex-flow: row wrap;

4. justify-content

Aligns flex items along the main axis (horizontal by default). Values include:

  • flex-start: Items are aligned to the start (default).

  • flex-end: Items are aligned to the end.

  • center: Items are centered.

  • space-between: Equal space between items.

  • space-around: Equal space around items.

  • space-evenly: Equal space between and around items.

5. align-items

Aligns flex items along the cross axis (perpendicular to the main axis). Values include:

  • flex-start, flex-end, center, baseline, stretch (default).

6. align-content

Aligns multiple lines of flex items (when wrapping occurs). Values are similar to justify-content:

  • flex-start, flex-end, center, space-between, space-around, stretch.