Practice
Resources
Contests
Online IDE
New
Free Mock
Events New Scaler
Practice
Improve your coding skills with our resources
Contests
Compete in popular contests with top coders
logo
Events
Attend free live masterclass hosted by top tech professionals
New
Scaler
Explore Offerings by SCALER
exit-intent-icon

Download Interview guide PDF

Before you leave, take this CSS Interview Questions interview guide with you.
Get a Free Personalized Career Roadmap
Answer 4 simple questions about you and get a path to a lucrative career
expand-icon Expand in New Tab
/ Interview Guides / CSS Interview Questions

CSS Interview Questions

Last Updated: Dec 20, 2024

Download PDF


Your requested download is ready!
Click here to download.
Certificate included
About the Speaker
What will you Learn?
Register Now

What is CSS?

CSS stands for Cascading Style Sheet. It’s a style sheet language that determines how the elements/contents in the page are looked/shown. CSS is used to develop a consistent look and feel for all the pages.

CSS was developed and is maintained by the World Wide Web Consortium (W3C). It was first released on December 17, 1996. The CSS Working group currently working with different browser vendors to add/enforce the new feature/ specifications in all the browsers.

CSS enables the separation of the content from the presentation. This separation provides a lot of flexibility and control over how the website has to look like. This is the main advantage of using CSS.

CSS3 or Cascading Style Sheets Level 3 is the third version of the CSS standard that is used to style and format web pages. CSS3 incorporates CSS2 standard with some improvements over it. The main change in CSS3 is the inclusion of divisions of standards into different modules that makes CSS3 easier to learn and understand. Learn More.

This article covers the most frequently asked CSS and CSS3 interview questions for freshers and experienced candidates.

CSS Interview Questions For Freshers

1. What are the advantages of using CSS?

The main advantages of CSS are given below:

  • Separation of content from presentation - CSS provides a way to present the same content in multiple presentation formats in mobile or desktop or laptop.
  • Easy to maintain - CSS, built effectively can be used to change the look and feel complete by making small changes. To make a global change, simply change the style, and all elements in all the web pages will be updated automatically.
  • Bandwidth - Used effectively, the style sheets will be stored in the browser cache and they can be used on multiple pages, without having to download again.
Create a free personalised study plan Create a FREE custom study plan
Get into your dream companies with expert guidance
Get into your dream companies with expert..
Real-Life Problems
Prep for Target Roles
Custom Plan Duration
Flexible Plans

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

There are different ways to specify units in CSS like px, em, pt, percentage (%). px(Pixel) gives fine-grained control and maintains alignment because 1 px or multiple of 1 px is guaranteed to look sharp. px is not cascade. em maintains relative size. you can have responsive fonts. Em, will cascade 1em is equal to the current font-size of the element or the browser default. If u sent font-size to 16px then 1em = 16px. The common practice is to set default body font-size to 62.5% (equal to 10px).

pt(point) are traditionally used in print. 1pt = 1/72 inch and it is a fixed-size unit.

%(percentage) sets font-size relative to the font size of the body. Hence, you have to set the font-size of the body to a reasonable size.

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

A rectangle box is wrapped around every HTML element. The box model is used to determine the height and width of the rectangular box. The CSS Box consists of Width and height (or in the absence of that, default values and the content inside), padding, borders, margin.

 
  • Content:  Actual Content of the box where the text or image is placed.
  • Padding: Area surrounding the content (Space between the border and content).
  • Border: Area surrounding the padding.
  • Margin: Area surrounding the border.
You can download a PDF version of Css Interview Questions.

Download PDF


Your requested download is ready!
Click here to download.

4. What are the limitations of CSS?

Disadvantages of CSS are given below:

  • Browser Compatibility: Some style selectors are supported and some are not. We have to determine which style is supported or not using the @support selector).
  • Cross Browser issue: Some selectors behave differently in a different browser).
  • There is no parent selector: Currently, Using CSS, you can’t select a parent tag.

5. How to include CSS in the webpage?

There are different ways to include a CSS in a webpage, 

1 - External Style Sheet: An external file linked to your HTML document: Using link tag, we can link the style sheet to the HTML page.

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

2 - Embed CSS with a style tag: A set of CSS styles included within your HTML page.

<style type="text/css">

/*Add style rules here*/

</style>

Add your CSS rules between the opening and closing style tags and write your CSS exactly the same way as you do in stand-alone stylesheet files.

3 - Add inline styles to HTML elements(CSS rules applied directly within an HTML tag.): Style can be added directly to the HTML element using a style tag.

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

4 - Import a stylesheet file (An external file imported into another CSS file): Another way to add CSS is by using the @import rule. This is to add a new CSS file within CSS itself.

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

Learn via our Video Courses

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

A CSS selector is the part of a CSS ruleset that actually selects the content you want to style. Different types of selectors are listed below.

Universal Selector: The universal selector works like a wildcard character, selecting all elements on a page. In the given example, the provided styles will get applied to all the elements on the page.

* {
  color: "green";
  font-size: 20px;
  line-height: 25px;
}

Element Type Selector: This selector matches one or more HTML elements of the same name. In the given example, the provided styles will get applied to all the ul elements on the page.

ul {
  line-style: none;
  border: solid 1px #ccc;
}

ID Selector: This selector matches any HTML element that has an ID attribute with the same value as that of the selector. In the given example, the provided styles will get applied to all the elements having ID as a container on the page.

#container {
  width: 960px;
  margin: 0 auto;
}

<div id="container"></div>

Class Selector: The class selector also matches all elements on the page that have their class attribute set to the same value as the class.  In the given example, the provided styles will get applied to all the elements having ID as the box on the page.

.box {
  padding: 10px;
  margin: 10px;
  width: 240px;
}

<div class="box"></div>

Descendant Combinator: The descendant selector or, more accurately, the descendant combinator lets you combine two or more selectors so you can be more specific in your selection method.

#container .box {
	float: left;
	padding-bottom: 15px;
} 

<div id="container">
	<div class="box"></div>
	
	<div class="box-2"></div>
</div>

<div class=”box”></div>

This declaration block will apply to all elements that have a class of box that is inside an element with an ID of the container. It’s worth noting that the .box element doesn’t have to be an immediate child: there could be another element wrapping .box, and the styles would still apply.

Child Combinator: A selector that uses the child combinator is similar to a selector that uses a descendant combinator, except it only targets immediate child elements.

#container> .box {
	float: left;
	padding-bottom: 15px;
}

<div id="container">
	<div class="box"></div>
	
	<div>
		<div class="box"></div>
	</div>
</div>

The selector will match all elements that have a class of box and that are immediate children of the #container element. That means, unlike the descendant combinator, there can’t be another element wrapping .box it has to be a direct child element.

General Sibling Combinator: A selector that uses a general sibling combinator to match elements based on sibling relationships. The selected elements are beside each other in the HTML.

h2 ~ p {
	margin-bottom: 20px;
}

<h2>Title</h2>
<p>Paragraph example.</p>
<p>Paragraph example.</p>
<p>Paragraph example.</p>
<div class=”box”>
	<p>Paragraph example.</p>
</div>

In this example, all paragraph elements (<p>) will be styled with the specified rules, but only if they are siblings of <h2> elements. There could be other elements in between the <h2> and <p>, and the styles would still apply.

Adjacent Sibling Combinator: A selector that uses the adjacent sibling combinator uses the plus symbol (+), and is almost the same as the general sibling selector. The difference is that the targeted element must be an immediate sibling, not just a general sibling.

p + p {
	text-indent: 1.Sem;
	margin-bottom: 0;
}

<h2>Title</h2>
<p>Paragraph example.</p>
<p>Paragraph example.</p>
<p>Paragraph example.</p>

<div class=”box”>
	<p>Paragraph example.</p>
	<p>Paragraph example.</p>
</div>

The above example will apply the specified styles only to paragraph elements that immediately follow other paragraph elements. This means the first paragraph element on a page would not receive these styles. Also, if another element appeared between two paragraphs, the second paragraph of the two wouldn’t have the styles applied.

Attribute Selector: The attribute selector targets elements based on the presence and/or value of HTML attributes, and is declared using square brackets.

input [type=”text”] {
	background-color: #444;
	width: 200px;
}

<input type="text">

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

A CSS Preprocessor is a tool used to extend the basic functionality of default vanilla CSS through its own scripting language. It helps us to use complex logical syntax like – variables, functions, mixins, code nesting, and inheritance to name a few, supercharging your vanilla CSS.

SASS: Sass is the acronym for “Syntactically Awesome Style Sheets”. SASS can be written in two different syntaxes using SASS or SCSS

SASS vs SCSS

  • SASS is based on indentation and SCSS(Sassy CSS) is not.
  • SASS uses .sass extension while SCSS uses .scss extension.
  • SASS doesn’t use curly brackets or semicolons. SCSS uses it, just like the CSS.

SASS Syntax

$font-color: #fff 
$bg-color: #00f

#box
	color: $font-color
	background: $bg-color

SCSS Syntax

$font-color: #fff;
$bg-color: #00f;

#box{
	color: $font-color;
	background: $bg-color;
}

LESS: LESS is an acronym for “Leaner Stylesheets”. LESS is easy to add to any javascript projects by using NPM or less.js file. It uses the extension .less.

LESS syntax is the same as the SCSS with some exceptions. LESS uses @ to define the variables.

@font-color: #fff;
@bg-color: #00f

#box{
	color: @font-color;
	background: @bg-color;
}

Stylus: Stylus offers a great deal of flexibility in writing syntax, supports native CSS as well as allows omission of brackets, colons, and semicolons. It doesn’t use @ or $ for defining variables.

/* STYLUS SYNTAX WRITTEN LIKE NATIVE CSS */
font-color= #fff;
bg-color = #00f;

#box {
	color: font-color;
	background: bg-color;
}

/* OR */

/* STYLUS SYNTAX WITHOUT CURLY BRACES */
font-color= #fff;
bg-color = #00f;

#box
	color: font-color;
	background: bg-color;
Advance your career with   Mock Assessments Refine your coding skills with Mock Assessments
Real-world coding challenges for top company interviews
Real-world coding challenges for top companies
Real-Life Problems
Detailed reports

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

It’s a CSS unit used to measure the height and width in percentage with respect to the viewport. It is used mainly in responsive design techniques. The measure VH is equal to 1/100 of the height of the viewport. If the height of the browser is 1000px, 1vh is equal to 10px. Similarly, if the width is 1000px, then 1 vw is equal to 10px.

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

Reset CSS: CSS resets aim to remove all built-in browser styling. For example margins, paddings, font-sizes of all elements are reset to be the same. 

Normalize CSS: Normalize CSS aims to make built-in browser styling consistent across browsers. It also corrects bugs for common browser dependencies.

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

Block Element: The block elements always start on a new line. They will also take space for an entire row or width. List of block elements are <div>, <p>.

Inline Elements: Inline elements don't start on a new line, they appear on the same line as the content and tags beside them. Some examples of inline elements are <a>, <span> , <strong>, and <img> tags. 

Inline Block Elements: Inline-block elements are similar to inline elements, except they can have padding and margins and set height and width values.

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

It’s most important to test a website in different browsers when you’re first designing it, or when making major changes. However, it’s also important to repeat these tests periodically, since browsers go through a lot of updates and changes.

12. What are Pseudo elements and Pseudo classes?

Pseudo-elements allows us to create items that do not normally exist in the document tree, for example ::after.

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

In the below example, the color will appear only on the first line of the paragraph.

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

Pseudo-classes select regular elements but under certain conditions like when the user is hovering over the link.

  • :link
  • :visited
  • :hover
  • :active
  • :focus

Example of the pseudo-class, In the below example, the color applies to the anchor tag when it’s hovered.

/* mouse over link */
a:hover {
	color: #FFOOFF;
}

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

No, it doesn’t affect the inline elements. Inline elements flow with the contents of the page.

14. What is cascading in CSS?

“Cascading” refers to the process of going through the style declarations and defining weight or importance to the styling rules that help the browser to select what rules have to be applied in times of conflict. The conflict here refers to multiple rules that are applicable to a particular HTML element. In such cases, we need to let the browser know what style needs to be applied to the element. This is done by cascading down the list of style declarations elements.

For example, if we have the below style:

and we also have the following declaration below it or in another stylesheet that has been linked to the page:

We have a conflict in color property here for the paragraph elements. Here, the browser just cascades down to identify what is the most recent and most specific style and applies that. Since we have the color:black; as the most specific declaration, the color black is applied to the paragraph elements. Now if you want to ensure color white is applied to the paragraph, we can define weight to that style by adding !important as shown below:

!important ensures that the property has the maximum weight in presence of other conflicting properties.

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

We can use the font-family property for achieving this. The font-family property is used for specifying what font needs to be applied on the targetted DOM element. It can hold several font names as part of “fallback” mechanism in case the browser does not support the fonts. For example, we can use:

In the above piece of code, we are applying font-family property to the paragraph element.

  • It tells the browser to look for “Times New Roman” font and apply it.
  • If the “Times New Roman” font is not installed or supported, then it asks the browser to use Times font.
  • If both “Times New Roman” and Times are not supported, then it asks the browser to use any supported generic font belonging to serif.

If you do not want the font-face of the paragraph element to be Times New Roman/Times/serif font, and you want to use the Arial/Helvetica/sans-serif font, then we can just update the CSS property of paragraph element as:

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

Adaptive Design Responsive Design
Adaptive design focuses on developing websites based on multiple fixed layout sizes. Responsive design focuses on showing content on the basis of available browser space.
When a website developed using adaptive design is opened on the desktop browser, first the available space is detected and then the layout with most appropriate sizes are picked and used for the display of contents. Resizing of browser window has no affect on the design. When a website developed using responsive design is opened on a desktop browser and when we try to resize the browser window, the content of the website is dynamically and optimally rearranged to accomodate the window.
Usually, adaptive designs use six standard screen widths - 320 px, 480 px, 760 px, 960 px, 1200 px, 1600 px. These sizes are detected and appropriate layouts are loaded. This design makes use of CSS media queries for changing styles depending on the target devices properties for adapting to different screens.
It takes a lot of time and effort to first examine the options and realities of the end users and then design best possible adaptive solutions them. Generally, Responsive design takes much less work to build and design fluid websites that can accomodate content from screen depending on the screen size.
Gives a lot of control over the design to develop sites for specific screens. No much control over the design is offered here.

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

The order of matching selectors goes from right to left of the selector expression. The elements in the DOM are filtered by browsers based on the key selectors and are then traversed up to the parent elements for determining the matches. The speed of determining the elements depends on the length of the chain of selectors. Consider an example:

Here, the browser first finds all span elements in the DOM and then it traverses to each of its parent elements to check if they are the paragraph p elements.

Once the browser finds all matching span tags having paragraph elements as parent and applies the color of black to the content, the matching process is stopped.

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

content-box is the default value box-sizing property. The height and the width properties consist only of the content by excluding the border and padding. Consider an example as shown:

div{
    width:300px;
    height:200px;
    padding:15px;
    border: 5px solid grey;
    margin:30px;
    -moz-box-sizing:content-box;
    -webkit-box-sizing:content-box;
    box-sizing:content-box;
}

Here, the box-sizing for the div element is given as content-box. That means, the height and width considered for the div content exclude the padding and border. We will get full height and width parameters specified for the content as shown in the below image.

The border-box property includes the content, padding and border in the height and width properties. Consider an example as shown:

Here, the box-sizing for the div element is given as border-box. That means the height and width considered for the div content will also include the padding and border. This means that the actual height of the div content will be:

actual height = height - 
                padding on top and bottom - 
                border on top and bottom
              = 200 - (15*2) - (5*2) 
              = 160 px

and the actual width of the div content would be:

This is represented in the image below:

19. How is opacity specified in CSS3?

Opacity refers to the degree to which the content is transparent or opaque. We can use the property named opacity which takes the values ranging from 0 to 1. 0 specifies that the element is completely transparent where 1 means that the element is completely opaque. We can use the opacity property as follows:

In the above example, an opacity of 60% is applied to the div section. The opacity property is not supported by the internet explorer browser. To make it work there, we need to use filter property as polyfill as shown in the example below.

20. Why should we use float property in CSS?

The float property is used for positioning the HTML elements horizontally either towards the left or right of the container. For instance,

Here, the element to which the class is applied ensures that the element is positioned on the right of the container. If you specify the value of float as left, then the element will be placed on the left side of the container.

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

z-index is used for specifying the vertical stacking of the overlapping elements that occur at the time of its positioning. It specifies the vertical stack order of the elements positioned that helps to define how the display of elements should happen in cases of overlapping.

The default value of this property is 0 and can be either positive or negative. Apart from 0, the values of the z-index can be:

  • Auto: The stack order will be set equal to the parent.
  • Number: The number can be positive or negative. It defines the stack order.
  • Initial: The default value of 0 is set to the property.
  • Inherit: The properties are inherited from the parent.

The elements having a lesser value of z-index is stacked lower than the ones with a higher z-index.

From the above figure, we can see that as the value of the z-index increases along the z-axis, the order of stacking would be towards the top of other elements along the vertical axis.

22. What do the following CSS selectors mean?

  1. div, p
  2. div p
  3. div ~ p
  4. div + p
  5. div > p

The meaning of the given list of selectors goes as follows:

  • div, p: This selector implies selecting all div elements and all p elements.

Consider an example below:

Here, all the div elements and the p elements would be selected by the browser irrespective of their parents or where they are placed. The remaining tags like h1 and span are ignored.

  • div p : This selector tells to select all p elements that are inside div elements. Consider an example below:

Here, <p> paragraph 1</p> and <p> Inner Div Paragraph </p> would be selected by the browser and the properties are applied. The rest of the paragraph tags are not selected.

  • div ~ p : This selector tells to select all p elements that have div elements preceeded anywhere. Consider an example,

Here, paragraph 2 and paragraph 3 elements would be selected as marked in the code above.

  • div + p : This selector says to select all p elements placed immediately after the div element. Consider an example in this case:

In this case, we have paragraph 2 element immediately after the div tag. Hence, only that element will be selected.

  • div > p : This selector says to select all p elements which has div as an immediate parent. In the same example below:

Only <p> paragraph 1</p> will be selected in this case because it has immediate div as the parent.

23. What are the properties of flexbox?

Flexbox stands for flexible box and it was introduced around 2017 in CSS with the purpose of providing an efficient way to handle layouts, align elements within them and distribute spaces amongst the items in dynamic/responsive conditions. It provides an enhanced ability to alter the dimensions of the items and make use of the available space in the container efficiently. In order to achieve this, CSS3 provides some properties.

The properties of flexbox are as follows:

  • flex-direction: This property helps in defining the direction the container should stack the items targetted for flex. The values of this property can be
    • row: Stacks items horizontally from left to right in the flex container.
    • column: Stacks items vertically from top to bottom in the flex container.
    • row-reverse: Stacks items horizontally from right to left in the flex container.
    • column-reverse: Stacks items vertically from bottom to top in the flex container.
  • flex-wrap: This property specifies of the flex items should be wrapped or not. Possible values are:
    • wrap: The flex items would be wrapped if needed.
    • nowrap: This is the default value that says the items won’t be wrapped.
    • wrap-reverse: This specifies that the items will be wrapped if needed but in reverse order.
  • flex-flow: This property is used for setting both flex-direction and flex-wrap properties in one statement.
  • justify-content: Used for aligning the flex items. Possible values are:
    • center: It means that all the flex items are present at the center of the container.
    • flex-start: This value states that the items are aligned at the start of the container. This is the default value.
    • flex-end: This value ensures the items are aligned at the end of the container.
    • space-around: This value displays the items having space between, before, around the items.
    • space-between: This value displays items with spaces between the lines.
  • align-items: This is used for aligning flex items.
  • align-content: This is used for aligning the flex lines.

24. What is the rem unit in CSS? How is it different from em?

The rem unit stands for “root em.” It is a relative unit that is calculated based on the font size of the root <html> element.

By default, most browsers set:

 

html font-size = 16px

So:

 

1rem = 16px 
2rem = 32px 
0.5rem = 8px

No matter where an element is placed in the page, rem always refers back to the root font size.

The em unit is also relative, but it depends on the font size of the parent element. Because of this, its value can increase when elements are nested.

Example:

 

.parent {
 font-size: 20px;
}
.child {
 font-size: 2em;
}

Here, the child becomes 40px (2 × 20px). If another element inside .child also uses 2em, it becomes 80px. The size keeps multiplying based on nesting.

With rem, that multiplication does not happen. The value stays tied to the root.

Example:

 

.child {
 font-size: 2rem;
}

Even inside multiple nested elements, 2rem always equals 2 × root font size.

Because of this consistency, rem is commonly used for layout spacing, typography systems, and scalable designs. em is useful when sizing needs to stay proportional to a specific component.

A common setup is:

 

html {
 font-size: 62.5%;
}

Since 62.5% of 16px equals 10px:

 

1rem = 10px

This makes calculations simple and predictable.

25. What is CSS inheritance? Which properties are inherited and which are not?

CSS inheritance means some properties automatically pass from a parent element to its children.

If a property is inherited, the child element uses the parent’s value unless it defines its own.

Example:

 

body {
 color: blue;
}

All text inside the body becomes blue unless another rule overrides it. The color property is inherited.

Most inherited properties are related to text and fonts. These include:

  • font-family
  • font-size
  • font-weight
  • font-style
  • color
  • line-height
  • text-align
  • text-transform
  • letter-spacing
  • word-spacing
  • visibility
  • cursor
  • list-style

Layout and box-model properties are not inherited automatically. These include:

  • margin
  • padding
  • border
  • width
  • height
  • display
  • position
  • background
  • overflow
  • float
  • z-index
  • box-sizing

For example, if a parent element has a border, the child does not automatically get that border.

Inheritance can be controlled using keywords.

inherit forces a property to take the value from its parent.

 

.child {
 border: inherit;
}

initial resets a property to its default browser value.

unset behaves like inherit for inherited properties and like initial for non-inherited properties.

It is also possible to reset most properties at once:

 

.element {
 all: unset;
}

Inheritance affects how styles cascade through the DOM and determines how much CSS needs to be written explicitly.

26. Explain the CSS display property comprehensively. What are all the possible values?

The display property defines how an element generates boxes in the layout and how it participates in the document flow.

The basic display types are:

1. block: Starts on a new line and takes full available width. Width and height can be set.

Examples: div, p, section, h1.

2. inline: Flows within text and does not start on a new line. Width and height cannot be set directly.

Examples: span, a, strong.

3. inline-block: Flows inline but allows width and height to be set.

Modern layout systems use:

4. flex: Creates a one-dimensional layout container. Child elements become flex items and can be aligned and distributed along a row or column.

 

.container {
 display: flex;
}

5. grid: Creates a two-dimensional layout container with rows and columns.

 

.container {
 display: grid;
}

6. inline-flex and inline-grid behave like flex and grid but remain inline-level elements.

Other important values include:

7. none: Removes the element completely from the layout. It takes no space and is not rendered.

8. list-item: Displays the element as a list item with a marker.

9. table, table-row, table-cell: Used to create table-like structures without actual <table> markup.

10. flow-root: Creates a new block formatting context. Often used to contain floated elements.

11. contents: Removes the element’s own box but keeps its children in the layout.

Here’s a common comparison:

  • display: none removes the element from layout completely.
  • visibility: hidden hides the element but keeps its space.
  • opacity: 0 makes the element transparent but keeps its space and allows animation.

The display property directly affects layout behavior, rendering, and spacing, which is why it is one of the most important CSS properties to understand clearly.

CSS Interview Questions for Experienced

1. Difference between CSS grid vs flexbox?

  • CSS Grid Layout is a two-dimensional system, meaning it can handle both columns and rows. Grid layout is intended for larger-scale layouts which aren’t linear in design.
  • Flexbox is largely a one-dimensional system (either in a column or a row). Flexbox layout is most appropriate to the components of an application.

2. Explain CSS position property?

  • Absolute: To place an element exactly where you want to place it. absolute position is actually set relative to the element's parent. if no parent is available then the relative place to the page itself (it will default all the way back up to the element).
  • Relative: "Relative to itself". Setting position: relative; on an element and no other positioning attributes, it will no effect on its positioning. It allows the use of z-index on the element and it limits the scope of absolutely positioned child elements. Any child element will be absolutely positioned within that block. 
  • Fixed: The element is positioned relative to the viewport or the browser window itself. viewport doesn't change if you scroll and hence the fixed element will stay right in the same position. 
  • Static: Static default for every single page element. The only reason you would ever set an element to position: static is to forcefully remove some positioning that got applied to an element outside of your control.
  • Sticky: Sticky positioning is a hybrid of relative and fixed positioning. The element is treated as relative positioned until it crosses a specified threshold, at which point it is treated as fixed positioned.
 

3. When does DOM reflow occur?

Reflow is the name of the web browser process for re-calculating the positions and geometries of elements in the document, for the purpose of re-rendering part or all of the document. 

Reflow occurs when:

  • Insert, remove or update an element in the DOM.
  • Modify content on the page, e.g. the text in an input box.
  • Move a DOM element.
  • Animate a DOM element.
  • Take measurements of an element such as offsetHeight or getComputedStyle.
  • Change a CSS style.

4. Different Box Sizing Property?

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

  • Content-box: The default width and height values apply to the element's content only. The padding and border are added to the outside of the box.
  • Padding-box: Width and height values apply to the element's content and its padding. The border is added to the outside of the box. Currently, only Firefox supports the padding-box value.
  • Border-box: Width and height values apply to the content, padding, and border.

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

  • Centering with Table:

HTML:

<div class=”cn”><div class=”inner”>your content</div></div>

CSS:

.cn {
	display: table-cell;
	width: 500px;
	height: 500px;
	vertical-align: middle;
	text-align: center;
}

.inner {
	display: inline-block;
	width: 200px; height: 200px;
}
  • Centering with Transform

HTML:

<div class="cn"><div class="inner">your content</div></div>

CSS:

.cn {
	position: relative;
	width: 500px;
	height: 500px;
}

.inner {
	position: absolute;
	top: 50%; left: 50%;
	transform: translate(-50%,-50%);
	width: 200px;
	height: 200px;
}
  • Centering with Flexbox

HTML:

<div class="cn"><div class="inner">your content</div></div>

CSS:

.cn {
	display: flex;
	justify-content: center;
	align-items: center;
}
  • Centering with Grid

HTML:

<div class=”wrap_grid”>
	<div id=”container”>vertical aligned text<br />some more text here
	</div>
</div>

CSS:

.wrap-grid {
	display: grid;
	place-content: center;
}

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

The four types of @media properties are:

  1. All → It’s the default property. Used for all media-type devices.
  2. Screen → Used for computer screen, mobile screen.
  3. Print → Used for printers.
  4. Speech → Used for screen readers.

7. What is the grid system?

CSS Grid Layout is the most powerful layout system available in CSS. It is said to be a 2-dimensional system, meaning it can handle both columns and rows, unlike flexbox which is largely a 1-dimensional system.

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

  • Using display property(display: none). It’s not available for screen readers. The element will not exist in the DOM if display: none is used.
  • Using visibility property(visibility: hidden), will take up the space of the element. It will be available to screen reader users. The element will actually be present in the DOM, but not shown on the screen.
  • Using position property (position: absolute). Make it available outside the screen.

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

The :root selector allows you to target the highest-level “parent” element in the DOM, or document tree. It is defined in the CSS Selectors Level 3 specification.

10. What does Accessibility (a11y) mean?

Accessibility refers to how software or hardware combinations are designed to make a system accessible to persons with disabilities, such as visual impairment, hearing loss, or limited dexterity.

For example, a website developed with accessibility in mind might have text-to-speech capabilities. In the USA public websites have to have accessible compliance. It’s defined in 508 compliance. It gives the guidelines and best practices for all website users that should be met with key areas of accessibility.

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

The keyword initial can be used to reset it to its default value.

12. How does Calc work?

The CSS3 calc() function allows us to perform mathematical operations on property values. Instead of declaring, for example, static pixel values for an element's width, we can use calc() to specify that the width is the result of the addition of two or more numeric values.

.foo {
	Width: calc(100px + 50px)
}

13. What do CSS Custom properties variables mean?

Custom properties (sometimes referred to as CSS variables or cascading variables) are defined by users that contain specific values to be reused throughout a document. The value is set using -- notion. And the values are accessed using the var() function.

:root {
	--main-bg-color: brown
}

.one {
	color: white;
	background-color· var (--main-bg-color);
	margin: l0px,
	width: 50px,
	height: 5Opx;
	display: inline-block;
}

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

  • CSS variables can be used without the need for a preprocessor. Currently, all the major browsers support the CSS variables. 
  • CSS variable cascade. But the preprocessor variables don’t cascade. 
  • CSS variable can be accessed and manipulated in javascript.

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

  • It makes every element in the document include the padding and border in the element’s inner dimension for the height and width computation.  
  • In box-sizing: border-box, The height of an element is now calculated by the content's height + vertical padding + vertical border width.
  • The width of an element is now calculated by the content's width + horizontal padding + horizontal border width.

16. What does !important mean in CSS?

The style is having the important will have the highest precedence and it overrides the cascaded property.

17. What is specificity? How to calculate specificity?

A process of determining which CSS rule will be applied to an element. It actually determines which rules will take precedence. Inline style usually wins then ID then the class value (or pseudo-class or attribute selector), the universal selector (*) has no specificity. ID selectors have a higher specificity than attribute selectors.

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

Progressive rendering is the name given to techniques used to improve the performance of a webpage (in particular, improve perceived load time) to render content for display as quickly as possible.

We can implement the progressive rendering of the page by loading the lazy loading of the images.  We can use Intersection Observer API to lazy load the image. The API makes it simple to detect when an element enters the viewport and take an action when it does. Once the image enters the viewport, we will start loading the images.

A sample snippet is given below.

<img class="lazy"
src="placeholder-image.jpg"
data-src="image-to-lazy-load-1x.jpg"
data-srcset="image-to-lazy-load-2x.jpg 2x, image-to-lazy-load-1x.jpg 1x"
alt="I'm an image!">

document.addEventListener("DOMContentLoaded", function() {
  var lazyImages = [].slice.call(document.querySelectorAll("img.lazy"));

  if ("IntersectionObserver" in window) {
    let lazyImageObserver = new IntersectionObserver(function(entries, observer) {
      entries.forEach(function(entry) {
        if (entry.isIntersecting) {
          let lazyImage = entry.target;
          lazyImage.src = lazyImage.dataset.src;
          lazyImage.srcset = lazyImage.dataset.srcset;
          lazyImage.classList.remove("lazy");
          lazyImageObserver.unobserve(lazyImage);
        }
      });
    });

    lazyImages.forEach(function(lazyImage) {
      lazyImageObserver.observe(lazyImage);
    });
  } else {
    // Possibly fall back to event handlers here
  }
});

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

Translate() does not cause the browser to trigger repaint and layout and instead only acts on the compositor. The absolute position triggers the repaint or DOM reflow. So, translate() gives better performance.

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

<head>
	<link h ref=" stylel. css" rel=" stylesheet">
	<link href="style2.css" rel="stylesheet">
</head>

No, the browsers will download the CSS in the order of its appearance on the HTML page.

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

The @support in CSS can be very useful to scan if the current browser has support for a certain feature.

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

Different ways to fix browser-specific issues.

  • We can write browser-specific styles separately in different sheets and load that only when the specific browser is used. This makes use of the server-side rendering technique.
  • We can use auto-prefix for automatically adding vendor prefixes in the code.
  • We can also use normalize.css or reset CSS techniques.

There are some ways for avoiding browser compatibility issues too. They are as follows:

  • Validate HTML and CSS: We know that the code will be read, interpreted and handled differently by different browsers. We need to validate our HTML and CSS files for the missing closing tags, or missing semicolons in the syntaxes because there are chances that the old browsers will throw errors while rendering the code. We can avoid those errors by:
    • Maintaining well-aligned code that helps in easy readability.
    • Inserting comments at necessary places.
    • Make use of validation tools like Jigsaw CSS validator, W3C HTML Validators to identify syntax issues in the code.
  • Maintain Cross-Browser Compatibility in the Layouts: Cross-Browser compatibility is a must while developing web applications. We expect our application to be responsive across all devices, browsers and platforms. Some of the effects of layout incompatibilities are unresponsiveness of the layouts in mobile devices, the difference in layout rendering between modern and old browsers, etc. These incompatibilities can be avoided by using:
    • CSS Multi-Column layouts - For maintaining proper layouts w.r.t columns and containers.
    • HTML viewport metatag – For ensuring content is properly spanned across mobile devices.
    • CSS Flexbox and Grids - To layout child elements depending on the content and available space.
    • CSS resets stylesheets - For reducing browser inconsistencies in default line heights, font sizes, margins etc.
  • Check JavaScript Library issues: Ensure the libraries are used judiciously and the ones used are supported by the browsers.
  • Check DOCTYPE tag keyword: The DOCTYPE keyword is meant for defining rules of what needs to be used in the code. Older browser versions check for DOCTYPE tag at the beginning and if not found, the application rendering won't be proper.
  • Test on real devices: Although applications can be tested on virtual environments, it would be more beneficial if the testing is carried out on real devices and platforms. We can use tools like Testsigma for this purpose that enables us to test in real devices parallelly.

Conclusion

CSS plays the most important role in the field of web development. This is because CSS helps in achieving beautiful, responsive or adaptive websites depending on the business requirements. CSS helps in building lighter and flexible layouts that help in loading pages faster and making the content visually appealing. CSS is continuously evolving and is becoming more powerful thereby making it the most sought-after technology by various companies to develop websites. In this article, we have seen the most commonly asked interview questions in CSS, more particularly CSS3.

Useful Resources

23. How does this property work overflow: hidden?

The overflow property in CSS is used for specifying whether the content has to be clipped or the scrollbars have to be added to the content area when the content size exceeds the specified container size where the content is enclosed. If the value of overflow is hidden, the content gets clipped post the size of the container thereby making the content invisible. For example,

If the content of the div is very large and exceeds the height of 50px, the content gets clipped post 50px and the rest of the content is not made visible.

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

We can add the text-align: center property inside the parent div for aligning the contents horizontally. But it will not align the contents vertically. We can align the content vertically by making the parent element have relative positioning and the child element have absolute positioning. The child element should have the values of top, bottom, right, left as 0 to center it in the middle vertically. Then we need to set the margin as auto. It is assumed that both the child and mother elements will have height and width values.

Consider we have a div element of height and width taking 20% of the screen size, and we have a paragraph element taking the height of 1.2em and width of 20%. If we want to align the paragraph element at the center (vertically and horizontally), we write the following styles:

25. How is margin different from padding in CSS?

Margin property using which we can create space around the elements. We can also create space for borders defined at the exteriors. We have the following properties for defining the margin:

  • margin-top
  • margin-right
  • margin-bottom
  • margin-left
    margin property by itself has the values as:
  • auto – The browser auto-calculates the margin while we use this.
  • length – The value of this property can be in px, pt, cm, em etc. The values can be positive or negative.
  • % – We can also give percentage value as margin to the element.
  • inherit – Using this property, the margin properties can be inherited from the parent elements.

The padding property is used for generating the space around the element’s content and inside any known border. The padding also has sub-properties like:

  • padding-top
  • padding-right
  • padding-bottom
  • padding-left

It is to be noted that the padding does not allow negative values.

From the below image, we can see that the Margin is the outermost entity of the CSS Box Model that lies outside of the borders whereas the padding lies within the borders.

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

We can use the concept of CSS counters. This lets us adjust the appearance of the content based on the location in a document. While using this, we need to first initialize the value of the counter-reset property which is 0 by default. The same property is also used for changing the value to any number that we need. Post initialization, the counter’s value can be incremented or decremented by using the counter-increment property. The name of the counter cannot be CSS keywords like “none”, “initial”, “inherit” etc. If the CSS keywords are used, then the declaration would be ignored.

Consider an example as shown below:

Here, we are trying to achieve auto count increment and display feature for the h2 tag. Wherever we use h2 tag, the content will be prefixed by "Header 1 : " , "Header 2 : ", "Header 3 : " etc.

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

Both are pseudo-classes (Pseudo-classes are those keywords that specifies the special state of the selected element). The nth-child() pseudo-class is used for matching elements based on the number that represents the position of an element based on the siblings. The number is used to match an element on the basis of the element’s position amongst its siblings.

For example, in the below piece of code, if we give nth-child(4) for the example class, then the 4th child of the example class is selected irrespective of the element type. Here, the fourth child of the example class is the div element. The element is selected and a background of black is added to it.

The nth-of-type() pseudo-class is similar to the nth-child but it helps in matching the selector based on a number that represents the position of the element within the elements that are the siblings of its same type. The number can also be given as a function or give keywords like odd or even.

For example, in the below piece of code, if we give p:nth-of-type(even) for the example class, then all the even paragraph tags are selected within the example class and the style of background black is applied to them. The selected elements are marked in comments in the below code:

28. What is the importance of CSS Sprites?

CSS sprites are used for combining multiple images in a single larger image. They are commonly used for representing icons that are used in the user interfaces. The main advantages of using sprites are:

  • It reduces the number of HTTP requests to get data of multiple images as they are acquired only by sending a single request.
  • It helps in downloading assets in advance that help display icons or images upon hover or other pseudo-states.
  • When there are multiple images, the browser makes separate calls to get the image for each of them. Using sprites, the images are combined in one and we can just call for that image using one call.

Consider an example where our application requires 3 images as shown below (Without Sprites Section). If we are trying to load the images independently, we require 3 different HTTP Requests to get the data. But if we have CSS Sprites where all 3 images are combines into 1 separated by some spaces, then we require only 1 HTTP Request.

We can access each image from the sprite by accessing the positioning properties as shown in the below code:

<!DOCTYPE html>
<html>
<head>
<style>
#home-icon {
  left: 0px;
  width: 46px;
  background: url('spriteFile.gif') 0 0;
}

#prev-icon {
  left: 63px;
  width: 43px;
  background: url('spriteFile.gif') -47px 0;
}

#next-icon {
  left: 129px;
  width: 43px;
  background: url('spriteFile.gif') -91px 0;
}
</style>
</head>
<body>

<img id="home-icon" src="spriteFile.gif" width="1" height="1">    <!-- To display home icon here -->
<img id="next-icon" src="spriteFile.gif" width="1" height="1">    <!-- To display next icon icon here -->
<img id="prev-icon" src="spriteFile.gif" width="1" height="1">    <!-- To display previous icon icon here -->

</body>
</html>

In the above code, we are trying to access each element - house, previous and next icon - from the sprite file by using the left, width properties. The image is displayed in the img section by means of the background property. Do note that the source of the image (src attribute of the img tag) is just one file which is the spriteFile.gif and depending on the rules specified in the id selectors, the images are loaded accordingly.

29. What do you understand by tweening in CSS?

Tweening is the process of filling the gaps between the key sequences, i.e between the keyframes that are already created. Keyframes are those frames that represent start and end point of animation action. Tweening involves generating intermediate keyframes between two images that give the impression that the first one has evolved smoothly to the second image. For this purpose, we use properties like transforms - matrix, translate, scale, rotate etc.

In the below example, we are generating intermediate frames of paragraph elements to slide through from the start to the right edge of the browser.

p {
  animation-duration: 2s;
  animation-name: slidethrough;
}

@keyframes slidethrough {
  from {
    margin-left: 100%;
    width: 300%; 
  }

  to {
    margin-left: 0%;
    width: 100%;
  }
}

Here, the paragraph element specifies that the animation process should take 2 seconds for execution from start to the finish. This is done by using the animation-duration property. The animation-name of the @keyframes is defined by using the property animation-name. The intermediate keyframes are defined by using @keyframes rule. In the example, we have just 2 keyframes. The first keyframe starts at 0% and runs till the left margin of 100% which is the rightmost edge of the containing element. The second keyframe starts at 100% where the left margin is set as 0% and the width to be set as 100% which results in finishing the animation flush against the left edge of the container area.

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

The clear property along with floats is used for specifying which side of floating elements is not supposed to float. An element having clear property ensures that the element does not move up adjacent to the float. But the element will be moved down past the float.

Let us understand this with the help of an example. We know that the floated objects do not add to the height of the objects where they reside. Consider we have a div element with class “floated_div” within another div element with id “main_div”.

<html>
    <head>
    <style>
        #main_div {
             width: 400px;
             margin: 10px auto;
             border: 4px solid #cccccc;
             padding: 5px;
        }

        .floated_div {
             float: left;
             width: 50px;
             height: 50px;
             border: 2px solid #990000;
             margin: 10px;
        }
    </style>
    </head>
    <body>
        <div id="main_div">
             <p>Clear Float Demo</p>
             <div class="floated_div"></div>
             <div class="floated_div"></div>
             <div class="floated_div"></div>
             <div class="floated_div"></div>
             <div class="floated_div"></div>
        </div>
    </body>
</html>

The result of this code would be as shown below. We see that the squares that are expected to be within dev are not within the main parent div. How do we fix this?

We can do it just by adding <div style="clear:both"></div> line at the end of the last floated element so that the floated elements are fit in properly within the main div container.

<html>
    <head>
    <style>
        #main_div {
             width: 400px;
             margin: 10px auto;
             border: 4px solid #cccccc;
             padding: 5px;
        }

        .floated_div {
             float: left;
             width: 50px;
             height: 50px;
             border: 2px solid #990000;
             margin: 10px;
        }
    </style>
    </head>
    <body>
        <div id="main_div">
             <p>Clear Float Demo</p>
            
             <div class="floated_div"></div>
             <div class="floated_div"></div>
             <div class="floated_div"></div>
             <div class="floated_div"></div>
             <div class="floated_div"></div>
             <div style="clear:both"></div>    <!-- Adding this fixed the issue -->
        </div>
    </body>
</html>

The result of this will be:

31. How does the absolute positioning work?

Absolute positioning is a very powerful positioning mechanism that allows users to place any element wherever they want in an exact location. The CSS properties right, left, top, bottom and define the exact locations where you need to place the element. In absolute positioning, the following points need to be considered:

  • The element to which the absolute positioning is applied is removed from the normal workflow of the HTML document.
    • The HTML layout does not create any space for that element in its page layout.
  • The element is positioned relative to the closest positioned ancestor. If no such ancestor is present, then the element is placed relative to the initial container block.
  • The final position of the element is determined based on values provided to the top, right, left, bottom.

32. What is the object-fit property in CSS? Explain all its values.

The object-fit property controls how replaced elements like <img> and <video> resize inside their container.

When you set a fixed width and height on an image, the image may stretch or distort. object-fit defines how the image should scale to fit that container.

Example:

 

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

The possible values are:

1. fill: This is the default value. The content stretches to fill the container completely. The aspect ratio is not preserved, so distortion can happen.

2. contain: The content scales to fit entirely inside the container while keeping its aspect ratio. No cropping occurs, but empty space (letterboxing) may appear on the sides or top/bottom.

3. cover: The content scales to completely cover the container while keeping its aspect ratio. Some parts may be cropped. This is commonly used for hero images and profile pictures.

4. none: The content keeps its original size. It does not resize. If it is larger than the container, it overflows.

5. scale-down: The browser compares none and contain and uses whichever results in a smaller image.

There is also a companion property called object-position. It controls how the image is aligned inside the container. The default is:

 

object-position: 50% 50%;

This means the image is centered.

Example of a circular avatar without distortion:

 

.avatar {
 width: 100px;
 height: 100px;
 object-fit: cover;
 border-radius: 50%;
}

The image fills the circle without stretching.

33. What are the :is(), :where(), and :not() pseudo-class functions in CSS?

These are modern pseudo-class functions introduced to make selectors more flexible and readable.

1. :is() -:is() allows grouping multiple selectors inside a single rule.

Example:

 

:is(h1, h2, h3) {
 color: blue;
}

This replaces:

 

h1, h2, h3 {
 color: blue;
}

The important detail is specificity. The specificity of :is() equals the most specific selector inside it.

Example:

 

:is(.card, #main) {
 padding: 20px;
}

Since #main has ID specificity, the whole rule takes that specificity.

:is() is also forgiving. If one selector inside it is invalid, the browser ignores only that part instead of discarding the entire rule.

2. :where() -:where() works the same way as :is(), but it always has zero specificity.

Example:

 

:where(.card, .panel) .title {
 font-size: 18px;
}

The specificity here comes only from .title, not from .card or .panel.

This makes :where() useful for writing base styles that should be easy to override later.

3. :not() - :not() selects elements that do not match the given selector.

Example:

 

button:not(.active) {
 opacity: 0.5;
}

This selects all buttons that do not have the class active.

In modern CSS, :not() can accept multiple selectors:

 

:not(.a, .b)

These pseudo-class functions can also be combined:

 

article :is(h1, h2):not(.subtitle) {
 margin-bottom: 10px;
}

This selects h1 or h2 inside an article, except those with class subtitle.

These selectors make stylesheets shorter and easier to maintain, especially in large projects.

34. What is the CSS filter property? What effects can you achieve with it?

The filter property applies graphical effects to an element, similar to image editing tools.

Example:

 

.image {
 filter: grayscale(100%);
}

This removes color from the image.

Common filter functions include:

  • blur(5px) - Applies blur effect.
  • brightness(1.5) - Adjusts brightness.
  • contrast(200%) - Changes contrast level.
  • grayscale(100%) - Removes color.
  • hue-rotate(90deg) - Shifts color tone.
  • invert(100%) - Inverts colors.
  • opacity(50%) - Adjusts transparency.
  • saturate(200%) - Increases color intensity.
  • sepia(100%) - Adds warm brown tone.
  • drop-shadow(4px 4px 10px rgba(0,0,0,0.5)) - Adds shadow following the element’s shape.

Multiple filters can be combined:

 

.image {
 filter: grayscale(100%) blur(2px);
}

There is also backdrop-filter, which applies effects to the content behind an element.

Example:

 

.glass {
 backdrop-filter: blur(10px);
}

This is used for frosted-glass effects.

Filters are often hardware-accelerated and create a compositing layer. They should be used carefully in animations or scroll-heavy pages to avoid performance issues.

HTML CSS Interview Questions

1. How does the HTML <img> element differ from CSS background-image? When should you use each?

The <img> element is part of the HTML structure. It represents actual content and appears in the DOM.

Key characteristics of <img>:

  • It is semantic.
  • It supports alt text for accessibility.
  • It is indexed by search engines.
  • It supports srcset and sizes for responsive images.
  • It supports native lazy loading using loading="lazy".
  • It contributes to layout and takes up space automatically.
  • It prints by default.

Example:

 

&lt;img src="photo.jpg" alt="Mountain landscape" loading="lazy"&gt;

CSS background-image is purely presentational. It is applied through CSS.

Example:

 

.card {
 background-image: url("photo.jpg");
}

Key characteristics of background-image:

  • It is decorative.
  • It does not support alt text.
  • It is not indexed as content.
  • It allows multiple backgrounds on one element.
  • It requires explicit width and height on the element.
  • It does not print by default.
  • It supports background-size: cover and contain.

A practical rule:

If the image conveys meaning or content, use <img>.

If the image is decorative or purely aesthetic, use background-image.

It is also possible to use <img> with object-fit: cover; to achieve background-like behavior while keeping semantic and accessibility benefits.

2. How do you style HTML form elements using CSS? What are the common challenges?

Form elements such as <input>, <select>, <textarea>, and <button> are partially controlled by the browser and operating system. Their appearance is not entirely defined by CSS, which creates styling challenges.

Common challenges include:

Different browsers render form controls differently. A <select> dropdown may look different in Chrome, Firefox, and Safari.

Some elements resist full styling control, such as:

  • <select> option dropdown list
  • <input type="date"> calendar picker
  • <input type="file"> upload button

To gain more control, developers often remove default styling using:

 

appearance: none;
-webkit-appearance: none;

This removes native styling and allows custom CSS design.

For checkboxes and radio buttons, a common technique is hiding the native control and styling a label or pseudo-element.

Example concept:

  • Set checkbox to opacity: 0 and position: absolute
  • Style label::before as the visible checkbox

Modern CSS provides the accent-color property, which simplifies styling of form controls:

 

input {
 accent-color: #0066ff;
}

This works for checkboxes, radio buttons, range inputs, and progress elements.

Useful pseudo-classes for form styling:

:focus applies when an element receives focus.

:focus-visible applies only when focus is triggered by keyboard navigation.

:placeholder-shown styles inputs when placeholder text is visible.

:valid, :invalid, and :required allow styling based on validation state.

Example:

 

input:invalid {
 border: 2px solid red;
}

Styling forms requires handling browser inconsistencies and sometimes combining CSS with custom markup for full control.

3. What is the Shadow DOM and how does it affect CSS scoping?

Shadow DOM is a web standard that allows encapsulating a part of the DOM and its CSS inside a component. It creates a separate DOM tree that is isolated from the main document.

When a shadow root is attached to an element using:

 

element.attachShadow({ mode: "open" });

a new DOM subtree is created. Styles written inside this shadow tree do not affect the main document, and styles from the main document do not leak into it.

This solves one of the long-standing issues in CSS: global scope. Normally, CSS rules can affect any matching element anywhere in the page. Shadow DOM prevents that.

However, there are important exceptions:

Inherited properties such as color and font-family still pass into the Shadow DOM because they are inherited by nature.

CSS custom properties (variables like --primary-color) also cross the shadow boundary. This allows theme control from outside.

Shadow DOM provides special selectors to control styling:

:host is used inside the shadow tree to style the host element.

 

:host {
 display: block;
}

:host-context(.dark-theme) allows styling based on an ancestor’s class outside the shadow root.

 

:host-context(.dark-theme) {
 background: black;
}

::part() allows external styling of specific parts that the component chooses to expose.

 

::part(button) {
 color: red;
}

Many UI libraries and Web Components use Shadow DOM for style encapsulation. Even some native browser elements such as <input type="range"> and <video> internally use Shadow DOM for their built-in UI.

Shadow DOM ensures component-level styling isolation while still allowing controlled customization.

4. What are HTML data-* attributes and how can they be used with CSS?

data-* attributes allow storing custom data directly inside HTML elements.

Example:

 

&lt;div data-status="active" data-count="5"&gt;&lt;/div&gt;

These attributes do not affect layout or behavior by default. They simply store extra information.

CSS can target them using attribute selectors:

 

[data-status="active"] {
 color: green;
}

Partial matching is also possible:

 

[data-status^="act"]   /* starts with */
[data-status$="ive"]   /* ends with */
[data-status*="tiv"]   /* contains */

CSS also provides the attr() function to read attribute values inside pseudo-elements:

 

.badge::after {
 content: attr(data-count);
}

This displays the value of data-count visually.

Currently, attr() works reliably only with the content property. Using it for properties like width or font-size has limited browser support.

JavaScript can access these attributes using:

 

element.dataset.status

A common use case is theming:

 

[data-theme="dark"] {
 background-color: black;
 color: white;
}

Instead of adding multiple classes, the theme can be controlled using a single attribute.

data-* attributes help connect HTML, CSS, and JavaScript in a structured and scalable way.

5. How do HTML5 semantic elements affect CSS styling and accessibility?

HTML5 introduced semantic elements such as:

<header>, <nav>, <main>, <section>, <article>, <aside>, <footer>, <figure>, <figcaption>, <details>, <summary>, <mark>, <time>

These elements provide meaning about the content they contain.

From a CSS perspective:

  • Most semantic elements behave like display: block by default.
  • They do not add extra visual styling.
  • They can be styled just like <div> elements.

Example:

 

nav {
 background-color: black;
}

The main advantage is cleaner and more meaningful selectors.

Instead of:

 

.article-container .header-div

You can write:

 

article &gt; header

This reduces unnecessary class names and improves readability.

From an accessibility perspective:

  • <nav> creates a navigation landmark.
  • <main> defines the primary content.
  • <header> may act as a banner.
  • <aside> represents complementary content.

Screen readers use these elements to build a navigation outline.

Search engines also use semantic structure to understand content hierarchy and importance.

Semantic HTML improves structure without changing visual styling behavior.

6. What is the difference between HTML presentational attributes and CSS properties for styling?

HTML presentational attributes were older ways of styling elements directly inside HTML tags.

Examples:

 

&lt;body bgcolor="red"&gt;
&lt;p align="center"&gt;Text&lt;/p&gt;
&lt;font size="5" color="blue"&gt;Hello&lt;/font&gt;
&lt;img border="1"&gt;

These attributes mix structure and presentation in the same file.

CSS replaces these with proper styling rules:

 

body {
 background-color: red;
}
p {
 text-align: center;
}
font {
 font-size: 20px;
 color: blue;
}
img {
 border: 1px solid black;
}

Key differences:

  • HTML defines structure. CSS defines appearance.
  • CSS allows one rule to style multiple elements.
  • CSS supports media queries and responsive design.
  • CSS provides cascade and specificity control.
  • CSS is easier to maintain and update.

Many presentational attributes such as bgcolor, align, <font>, and <center> are deprecated in HTML5.

Some attributes still remain valid, such as:

  • width and height on <img> (helps prevent layout shift)
  • type on <ol>

Modern development separates structure (HTML) and presentation (CSS) completely.

7. What is the Critical Rendering Path? How do HTML and CSS work together to render a web page?

The Critical Rendering Path (CRP) is the sequence of steps the browser follows to turn HTML and CSS into visible pixels on the screen.

When a browser loads a webpage, it does not immediately display content. It goes through a structured process:

  1. HTML Parsing -> DOM Tree

The browser reads the HTML file and converts it into a Document Object Model (DOM). The DOM is a tree structure representing all HTML elements.

  1. CSS Parsing -> CSSOM Tree

The browser reads CSS files and builds the CSS Object Model (CSSOM), which contains all style rules.

  1. DOM + CSSOM -> Render Tree

The DOM and CSSOM combine to form the Render Tree. Only visible elements are included here.

Elements with display: none are excluded.

Elements with visibility: hidden remain in the tree.
 

  1. Layout (Reflow)

The browser calculates the position and size of each element.

  1. Paint

The browser fills pixels - colors, borders, text, shadows, etc.

  1. Composite

Layers are merged in the correct stacking order (z-index, transforms, etc.).

CSS is render-blocking because the browser cannot paint anything until the CSSOM is fully constructed. Styles affect layout and appearance, so rendering waits for CSS to finish loading.

Common optimization strategies:

  • Inline critical CSS for above-the-fold content
  • Defer non-critical CSS
  • Reduce unnecessary DOM depth
  • Avoid forced layout recalculations

The Critical Rendering Path explains why CSS placement and loading strategy directly impact performance.

Advanced CSS Interview Questions

1. What is CSS Subgrid? How does it solve alignment problems in nested grids?

CSS Subgrid allows a grid item’s children to align to the parent grid’s tracks instead of creating their own independent grid tracks.

Without subgrid, nested grids do not share row and column alignment. Each grid calculates its own tracks separately. This often causes alignment issues in layouts like card grids.

Example problem:

Multiple cards in a grid contain title, body, and footer sections. Without subgrid, these internal rows do not align consistently across cards.

Subgrid solves this.

Example:

 

.card-grid {
 display: grid;
 grid-template-columns: repeat(3, 1fr);
 grid-template-rows: auto 1fr auto;
}
.card {
 display: grid;
 grid-template-rows: subgrid;
 grid-row: span 3;
}

Here, each card inherits the row structure from the parent grid. The title, body, and footer align across all cards.

Key behaviors:

  • Subgrid inherits the parent’s track sizing.
  • It inherits line names.
  • It inherits gap values by default.
  • Gap can be overridden using gap: 0; on the subgrid.
  • It can be applied to rows, columns, or both independently.

Common use cases:

Form layouts where labels and inputs must align across rows.

Dashboard cards where header and footer heights must match.

Navigation menus with aligned sub-items.

Subgrid removes the need for manual height adjustments or JavaScript-based alignment fixes in nested layouts.

2. Explain prefers-color-scheme and prefers-reduced-motion media features. How do they improve accessibility?

These are user preference media features that detect system-level accessibility or appearance settings.

prefers-color-scheme detects whether the user prefers light mode or dark mode.

Example:

 

@media (prefers-color-scheme: dark) {
 :root {
   --bg: #1a1a1a;
   --text: #f0f0f0;
 }
}

A common strategy is defining colors using CSS custom properties on :root, then overriding them inside the media query.

The color-scheme property can also be declared:

 

:root {
 color-scheme: light dark;
}

This tells the browser to adjust built-in UI elements such as scrollbars and form controls.

prefers-reduced-motion detects whether the user has enabled reduced motion in operating system accessibility settings.

Example:

 

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

This reduces animations that may cause motion sickness or discomfort.

Other related features include:

  • prefers-contrast
  • forced-colors
  • prefers-reduced-transparency

These features improve accessibility by respecting user-level preferences. They allow applications to adapt automatically without requiring manual theme switches.

3. How does the CSS will-change property work? When should and shouldn't you use it?

The will-change property informs the browser that a specific property of an element is likely to change soon. This allows the browser to prepare optimizations in advance.

Example:

 

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

Or:

 

.animating {
 will-change: transform, opacity;
}

When an element animates properties like transform or opacity, the browser may create a new compositing layer. If that layer is created at the moment the animation begins, the first frame can stutter. will-change allows the browser to create that layer earlier.

How it works:

  • The browser prepares GPU compositing for the specified property.
  • Rendering becomes smoother when the animation starts.
  • Memory usage increases because new layers are created.

When to use it:

Use it only when an element is about to animate.

Use it on specific elements, not globally.

When not to use it:

Do not apply will-change to many elements. Each layer consumes memory.

Do not use will-change: all. It prevents the browser from optimizing effectively.

Do not leave it permanently in stylesheets. It should be temporary.

A common pattern is applying it before animation and removing it afterward.

Example concept:

 

el.style.willChange = "transform";
el.addEventListener("animationend", () =&gt; {
 el.style.willChange = "auto";
});

will-change improves rendering smoothness but increases memory usage. It should be used carefully and only where performance issues are measurable.

4. What are CSS Logical Properties? Why should we use them over physical properties?

CSS Logical Properties define layout using writing-direction–aware terms instead of fixed physical directions like left, right, top, and bottom.

Traditional CSS uses physical properties such as:

  • margin-left
  • padding-right
  • width
  • height
  • top
  • left

These assume a left-to-right horizontal layout. Logical properties replace these with flow-relative equivalents that adapt automatically based on writing direction and writing mode.

For example, in a standard horizontal left-to-right layout:

  • margin-inline-start equals margin-left
  • margin-inline-end equals margin-right
  • margin-block-start equals margin-top
  • margin-block-end equals margin-bottom

Logical shorthands also exist:

  • margin-inline
  • margin-block
  • padding-inline
  • padding-block
  • border-inline
  • border-block

Size properties also change:

  • inline-size replaces width
  • block-size replaces height

Positioning equivalents:

  • inset-inline-start replaces left
  • inset-block-start replaces top

Example:

 

.sidebar {
 margin-inline-start: 2rem;
 padding-block: 1rem;
 inline-size: 300px;
}

This works correctly in:

  • Left-to-right layouts (English)
  • Right-to-left layouts (Arabic, Hebrew)
  • Vertical writing modes (Japanese, Chinese)

Why use logical properties:

They automatically adapt to different writing directions without needing separate RTL stylesheets.

They support vertical writing systems where block and inline axes switch.

They align with modern internationalized applications and global design systems.

They provide a clearer mental model:

  • Inline direction = direction text flows.
  • Block direction = stacking direction of elements.

Logical properties make layouts flexible and future-proof without duplicating styles for different languages.

5. What is the CSS clamp() function? How is it different from min() and max()?

The clamp() function restricts a value between a minimum and maximum while allowing it to scale fluidly.

Syntax:

 

clamp(MIN, PREFERRED, MAX)

It behaves like:

 

max(MIN, min(PREFERRED, MAX))

Example:

 

font-size: clamp(1rem, 2.5vw, 2rem);

The font size scales with viewport width (2.5vw) but never becomes smaller than 1rem and never larger than 2rem.

This is commonly used for fluid typography.

min() returns the smallest value:

 

width: min(90%, 1200px);

The width will be whichever is smaller.

max() returns the largest value:

 

padding: max(1rem, 5vw);

The padding will be whichever is larger.

Comparison:

  • clamp() sets both lower and upper limits.
  • min() sets a ceiling.
  • max() sets a floor.

Common patterns:

Fluid typography:

 

font-size: clamp(1rem, 1rem + 1vw, 1.5rem);

Responsive spacing:

 

gap: clamp(0.5rem, 2vw, 2rem);

Flexible containers:

 

width: clamp(300px, 50%, 800px);

These functions allow responsive behavior without writing media queries. They also accept mixed units directly, unlike older techniques that required complex calculations.

6. What are CSS Cascade Layers (@layer)? How do they affect specificity?

Cascade Layers allow grouping styles into ordered layers, giving control over precedence without relying on selector specificity tricks.

Layer order is defined first:

 

@layer reset, base, components, utilities;

Styles are then placed inside layers:

 

@layer base {
 a {
   color: blue;
 }
}
@layer components {
 .link {
   color: green;
 }
}

Layer rules:

  • Later layers override earlier layers.
  • This happens regardless of selector specificity.
  • Unlayered styles always override layered styles.
  • When using !important, earlier layers win over later ones.

This changes how CSS conflicts are resolved. A low-specificity selector in a later layer can override a high-specificity selector in an earlier layer.

Example concept:

A .btn class in the utilities layer can override a more complex selector in the reset layer simply because its layer is defined later.

This makes it easier to structure large projects, especially when working with third-party CSS. External libraries can be placed in early layers, and project-specific styles can be placed in later layers.

Cascade Layers make CSS architecture predictable and reduce the need for overly specific selectors.

7. Explain the CSS :has() pseudo-class. Why is it called the 'parent selector'?

:has() selects an element based on what it contains or what follows it. Before :has(), CSS could only select children based on parents, not the other way around.

Basic syntax:

 

parent:has(child) {
 /* styles */
}

Example:

 

div:has(&gt; img) {
 padding: 0;
}

This selects div elements that contain a direct child <img>.

It can also react to sibling relationships:

 

h1:has(+ p) {
 margin-bottom: 0;
}

This selects an h1 that is immediately followed by a p.

Another practical example:

 

form:has(:invalid) {
 border: 2px solid red;
}

This styles the entire form if any input inside it is invalid.

Multiple conditions can be combined:

 

article:has(h2):has(img) {
 border: 1px solid black;
}

This selects articles that contain both an h2 and an img.

Negation is also possible:

 

article:not(:has(img)) {
 background: #f5f5f5;
}

:has() is often called the “parent selector” because it allows selecting a parent based on its children, something that was not possible before.

Browsers optimize :has() internally, but complex selectors should still be used carefully in large documents.

8. What are CSS Container Queries? How do they differ from Media Queries?

Container Queries allow a component to change its styles based on the size of its parent container instead of the viewport.

Traditionally, responsive design relied on Media Queries, which respond to the viewport width. This works at the page level but does not help when a component appears in different layouts within the same page.

Container Queries solve this by making components context-aware.

To use them, you first define a container:

 

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

Then apply a container query:

 

@container card (min-width: 400px) {
 .card {
   flex-direction: row;
 }
}

Here, .card changes layout only when its container reaches 400px, regardless of viewport size.

container-type values:

  • inline-size - responds to width
  • size - responds to both width and height
  • normal - no size containment

Key differences from Media Queries:

  • Media Queries respond to viewport size.
  • Container Queries respond to parent container size.
  • Media Queries control page-level layout.
  • Container Queries control component-level layout.
  • The same component can render differently in a sidebar and in the main content area without JavaScript.

Container query units are also available:

  • cqw - 1% of container width
  • cqh - 1% of container height
  • cqi - 1% of container inline size
  • cqb - 1% of container block size

Container Queries are supported in all modern browsers since early 2023 and represent a major shift toward modular, reusable design systems.

CSS Important Interview Questions

1. What is the CSS pointer-events property? What are its use cases?

The pointer-events property controls whether an element responds to mouse and touch interactions.

Basic values:

  • auto - default behavior
  • none - element does not receive pointer events

When pointer-events: none; is applied, clicks pass through the element to whatever is behind it.

Example:

 

.overlay {
 pointer-events: none;
}

Common use cases:

Disabling interaction visually:

 

.btn--disabled {
 pointer-events: none;
 opacity: 0.5;
}

Creating decorative overlays that should not block clicks underneath.

Disabling links without removing the href:

 

a.inactive {
 pointer-events: none;
}

Creating watermarks or transparent UI layers that should not capture clicks.

Important caveats:

pointer-events: none does not prevent keyboard interaction. The element can still receive focus and be activated using the keyboard. For complete disabling, use:

  • tabindex="-1"
  • aria-disabled="true"

Child elements can override the parent’s setting. If a parent has pointer-events: none, but a child has pointer-events: auto, the child will still respond to interaction.

In SVG, additional values exist such as visiblePainted, stroke, fill, and others.

pointer-events is frequently used in UI layering and interaction control, especially in complex layouts.

2. What are CSS text-overflow, word-wrap, and overflow-wrap properties? How do you handle text overflow?

Text overflow happens when content exceeds the available space in its container. CSS provides multiple properties to control how text behaves.

text-overflow controls how hidden overflowed text is visually indicated.

Common values:

  • clip - cuts the text abruptly (default)
  • ellipsis - adds "..." at the end

For text-overflow: ellipsis to work, three conditions must be met:

 

.box {
 overflow: hidden;
 white-space: nowrap;
 text-overflow: ellipsis;
}

Without overflow: hidden and white-space: nowrap, ellipsis will not appear.

For multi-line truncation, the common pattern is:

 

.box {
 display: -webkit-box;
 -webkit-line-clamp: 3;
 -webkit-box-orient: vertical;
 overflow: hidden;
}

This limits text to three lines and adds ellipsis. Browser support varies slightly, but it works in modern browsers.

overflow-wrap (formerly word-wrap) controls whether long words can break inside themselves.

 

overflow-wrap: break-word;

This prevents long URLs or continuous strings from overflowing their container.

word-break gives more aggressive control:

  • break-all breaks between any characters.
  • keep-all prevents breaking in certain languages like CJK.

white-space controls how whitespace and line breaks behave:

  • normal - collapses spaces and allows wrapping
  • nowrap - prevents wrapping
  • pre - preserves spaces and line breaks
  • pre-wrap - preserves spaces but allows wrapping
  • pre-line - collapses spaces but preserves line breaks

The hyphens property can automatically insert hyphenation points:

 

p {
 hyphens: auto;
}

This works best when the lang attribute is set correctly on the HTML element.

Handling text overflow properly prevents layout breakage and improves readability, especially in dynamic content systems.

3. What is the difference between max-width and width? Why does max-width matter for responsive design?

The width property sets the exact width of an element. That width can be fixed (like 1200px) or relative (like 80%).

Example:

 

.container {
 width: 1200px;
}

Here, the container will always try to be 1200px wide. On small screens, this causes horizontal scrolling because the element cannot shrink below that value.

max-width works differently. It sets an upper limit. The element can become smaller, but it will never grow larger than the specified value.

Example:

 

.container {
 width: 100%;
 max-width: 1200px;
}

This means:

  • On small screens, the container becomes 100% of the screen width.
  • On large screens, it stops growing once it reaches 1200px.
  • It stays centered if combined with margin: 0 auto;.

Full responsive pattern:

 

.container {
 width: 100%;
 max-width: 1200px;
 margin: 0 auto;
}

This creates a layout that is fluid on mobile and capped on large screens without needing media queries.

Important behavior:

If both width and max-width are set and the width exceeds max-width, the max-width value wins.

Example:

 

.box {
 width: 1500px;
 max-width: 1200px;
}

The final width will be 1200px.

Common responsive image pattern:

 

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

This ensures images never overflow their container and scale proportionally.

Related properties:

  • min-width sets a lower limit.
  • min-height and max-height work the same way vertically.

One detail to remember:

Percentage-based max-width is relative to the containing block.
Viewport units like vw are relative to the viewport.

max-width is essential for responsive design because it prevents layout overflow while keeping content fluid.

4. What is the CSS transform property? Explain all transform functions.

The transform property applies geometric transformations to elements. It changes how an element appears visually without affecting the document flow.

2D transform functions:

translate(x, y) moves an element.
translateX() and translateY() move along a single axis.

 

transform: translate(50px, 20px);

rotate(angle) rotates an element.

 

transform: rotate(45deg);

scale(x, y) resizes an element.

 

transform: scale(1.5);

skew(x-angle, y-angle) tilts an element.

 

transform: skew(20deg);

3D transform functions:

  • rotateX(), rotateY(), rotateZ()
  • translate3d(x, y, z)
  • scale3d()
  • perspective()

Multiple transforms can be chained:

 

transform: translateX(50px) rotate(45deg) scale(1.2);

Transforms are applied from right to left.

The transform-origin property changes the pivot point.

 

transform-origin: top left;

By default, the origin is at the center.

From a performance perspective, transform and opacity are the safest properties to animate. They do not trigger layout recalculation and can be handled by the GPU, making them smoother than properties like width or margin.

5. How do CSS media queries work? Explain breakpoints and mobile-first approach.

CSS media queries apply styles only when certain conditions are met.@media (condition) {
/* rules */
}@media (min-width: 768px) {
.container {
  display: flex;
}
}@media (orientation: landscape) { }

 

 

@media (hover: hover) { }

Conditions can be combined:

 

@media (min-width: 768px) and (max-width: 1024px) { }

Common breakpoint ranges:

  • 320px - small mobile
  • 480px - standard mobile
  • 768px - tablet
  • 1024px - laptop
  • 1200px - desktop
  • 1440px - large desktop

Mobile-first approach:

Base CSS targets small screens.

Enhancements are added using min-width media queries.

Example:

 

.container {
 display: block;
}
@media (min-width: 768px) {
 .container {
   display: flex;
 }
}

This keeps the base design simple and progressively enhances layout for larger screens.

Desktop-first approach does the opposite by using max-width queries to simplify layouts for smaller screens.

Mobile-first is generally preferred because it prioritizes performance and progressive enhancement.

 

This applies styles only when the viewport is 768px or wider.

Feature-based queries are also possible:

 

 

 

Most common type is width-based:

 

 

Basic syntax:

 

 

6. What is BEM (Block Element Modifier) methodology in CSS? Why is it popular?

BEM is a naming convention for CSS classes that creates a clear structure for components. It stands for Block, Element, Modifier.block__element--modifier.card { }
.menu { }
.form { }.card__title { }
.card__image { }
.menu__item { }.card--featured { }
.menu__item--active { }
.button--large { }

 

Example in HTML:

 

&lt;div class="card card--featured"&gt;
 &lt;h2 class="card__title"&gt;Title&lt;/h2&gt;
 &lt;p class="card__body"&gt;Content&lt;/p&gt;
&lt;/div&gt;

Why BEM is widely used:

  • Class names describe structure clearly.
  • Selectors usually remain single-class (low specificity).
  • It avoids deep nesting and overly complex selectors.
  • Naming conflicts are minimized because blocks are self-contained.
  • It scales well in large projects where many developers work together.

Alternative methodologies exist, such as OOCSS, SMACSS, and utility-first approaches, but BEM remains popular because it is simple, readable, and framework-independent.

 

Modifier represents a variation or state.

 

 

 

Element represents a part of the block that depends on it.

 

 

 

Block represents a standalone component.

Example:

 

 

Format:

 

 

7. What are CSS transitions? How do they differ from CSS animations?

CSS transitions animate the change of a property between two states. The animation happens when a property value changes, for example on :hover, :focus, or when a class is added or removed.transition: property duration timing-function delay;.button {
background: blue;
transition: background 0.3s ease;
}
.button:hover {
background: red;
}@keyframes slide {
0%   { left: 0; }
50%  { left: 50%; }
100% { left: 100%; }
}
.box {
animation: slide 2s ease infinite;
}

 

Animations can:

  • Run automatically
  • Loop infinitely
  • Reverse direction
  • Pause and resume
  • Define multiple stages

Key differences:

  • Transitions require a state change to trigger.
  • Animations can start automatically.
  • Transitions move between two states only.
  • Animations can define multiple keyframes.
  • Transitions cannot loop.
  • Animations can repeat using animation-iteration-count.

Both transitions and animations perform best when animating transform and opacity, as those properties avoid layout recalculation.

 

When the button is hovered, the background color smoothly changes from blue to red over 0.3 seconds.

Timing functions control acceleration:

  • ease (default)
  • linear
  • ease-in
  • ease-out
  • ease-in-out
  • cubic-bezier()

CSS animations are more powerful. They use @keyframes and allow multiple intermediate steps.

Example:

 

 

 

Example:

 

 

Basic syntax:

 

 

CSS MCQ

1.

What would be the color of text “I am awesome” for the following rules?

2.

Which of the following is NOT a valid CSS length unit?

3.

Which of the following CSS properties DOES NOT influence the box model?

4.

Which CSS property allows you to hide an element but still maintain the space it occupies on the web page?

5.

What is the CSS selector which allows you to target every element in a web page?

6.

How would you select which anchor element will have href consisting of the substring “js”?

7.

Which among the below options are used for giving line over text?

8.

What property should be used in case we need to display a nice blue border that is dotted in nature around an image?

9.

Which of the below options are used for defining the difference between two lines of the content?

10.

How will you select the anchor element whose href attribute starts with https?

11.

Which among the below property is used for setting the blend mode of background layers in an element?

12.

Which among the following options represent correct syntax for selecting all paragraph elements in a div element?

13.

What CSS3 property is used for the set distance between borders of adjacent tables cells?

14.

What CSS3 property is used for capitalizing the text or converting them to lowercase or uppercase?

15.

In the following piece of code, does the stylesheet2.css sheet has to be loaded and parsed before the first p tag is loaded?

<head>
    <link href="stylesheet1.css" rel="stylesheet">
</head>
<body>
    <p>Paragraph 1</p>
    <p>Paragraph 2</p>
    <link href="stylesheet2.css" rel="stylesheet">
</body>
Excel at your interview with Masterclasses Know More
Certificate included
What will you Learn?
Free Mock Assessment
Fill up the details for personalised experience.
Phone Number *
OTP will be sent to this number for verification
+91 *
+91
Change Number
Graduation Year *
Graduation Year *
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
*Enter the expected year of graduation if you're student
Current Employer
Company Name
College you graduated from
College/University Name
Job Title
Job Title
Engineering Leadership
Software Development Engineer (Backend)
Software Development Engineer (Frontend)
Software Development Engineer (Full Stack)
Data Scientist
Android Engineer
iOS Engineer
Devops Engineer
Support Engineer
Research Engineer
Engineering Intern
QA Engineer
Co-founder
SDET
Product Manager
Product Designer
Backend Architect
Program Manager
Release Engineer
Security Leadership
Database Administrator
Data Analyst
Data Engineer
Non Coder
Other
Please verify your phone number
Edit
Resend OTP
By clicking on Start Test, I agree to be contacted by Scaler in the future.
Already have an account? Log in
Free Mock Assessment
Instructions from Interviewbit
Start Test