Cascading Style Sheets (CSS) is a building block technology for websites. It allows for arranging, colouring, and choosing fonts and other items on the pages visited. A good command of CSS is crucial to making any website visually appealing as well as responsive. You can gauge your depth of understanding through these CSS interview questions whether you are a beginner or an expert.
This blog provides a variety of CSS interview questions designed specifically for freshers and experienced individuals. Also, it touches upon fundamental topics, syntax examples and recent research in the field. This guide will help you get ready efficiently for your next CSS interview irrespective of your level.
CSS Interview Questions for Freshers
What are the advantages of using CSS?
CSS offers several benefits:
Separates content from presentation.
Reduces HTML code size, improving loading speed.
Simplifies maintenance by managing styles in one place.
How do you specify units in CSS, and what are the different ways to do it?
Units in CSS stand for attributes such as width, height, margin and padding sizes. The most common ways to define units are:
Absolute units: px (pixels), cm (centimetres), mm (millimetres).
Relative units: em (relative to the font size), rem (relative to the root font size), % (relative to the parent element), vw (1% of the viewport width), vh(1% of the viewport height).
How is CSS different from CSS3?
CSS is the original language for web development styles, while CSS3 is its latest version that brings with it new elements and capabilities. Advanced Compounds of CSS3 are Animations, transitions, gradients, Flexbox, Grid layout and support for responsive design. With these new components, web development becomes more efficient and visually appealing.
What are the limitations of CSS?
CSS has some limitations:
Cannot perform calculations or use logic.
Browser compatibility issues may lead to inconsistent behaviour.
Lacks dynamic capabilities, requiring JavaScript for interactive elements.
Cannot directly interact with server-side operations or databases.
How do you include CSS in a webpage?
CSS can be included in a webpage in three ways:
Inline CSS: Directly within an HTML element using the style attribute.
Internal CSS: Defined within a <style> tag inside the <head> section of the HTML file.
External CSS: A separate .css file linked with the <link> tag, allowing multiple pages to share the same styles.
List the different CSS frameworks
Several popular CSS frameworks help streamline the development process:
Bootstrap: A comprehensive framework with a grid system for responsive design.
Foundation: Offers advanced responsive features and accessibility tools.
Bulma: A modern, Flexbox-based framework for creating layouts.
Tailwind CSS: A utility-first framework allowing developers to build custom designs.
Materialize: Inspired by Google’s Material Design for creating sleek and interactive interfaces.
What is the Box Model in CSS, and which CSS properties are part of it?
The Box Model in CSS represents the structure of a rectangular box used to layout elements on a webpage. It consists of the following properties:
Content: The actual content of the element.
Padding: Space between the content and the border.
Border: The outer edge surrounding the padding.
Margin: Space outside the border that separates the element from others.
How can you use CSS to create a responsive button that changes colour on hover? Provide the code.
Compare various CSS text properties, including text-align, text-transform, and text-decoration.
Property
Description
Values
text-align
Aligns text horizontally within its container.
left, right, centre, justify
text-transform
Controls capitalization of text.
uppercase, lowercase, capitalise
text-decoration
Adds decorations to text (underline, overline, line-through).
underline, overline, line-through, none
Which type of CSS has the highest priority?
The priority of CSS styles is determined by specificity and source order. The highest priority is given to Inline CSS (styles defined directly within an HTML element), followed by IDs, classes, and elements. The !important declaration overrides all other styles but should be used carefully to avoid complications.
What is VH/VW (viewport height/viewport width) in CSS?
VH (Viewport Height) and VW (Viewport Width) are relative units in CSS used for responsive design.
1vh: Represents 1% of the viewport’s height.
1vw: Represents 1% of the viewport’s width.
These units allow elements to scale dynamically with the size of the screen or browser window.
How can we add comments in CSS?
/* symbol is used to start a comment and */ to end it. Comments help describe or explain the code making it easier to understand and maintain, and they are ignored by the browser.
/* This is a comment */
What is the difference between reset and normalize CSS?
Feature
Reset CSS
Normalize CSS
Purpose
Removes all default browser styles
Makes browser styles consistent across all browsers
Styling
Creates a completely blank slate for styling
Retains useful default styles while normalising them
Flexibility
Allows for full customization from scratch
Ensures compatibility with minimal adjustments
Browser Consistency
May cause issues with certain browser defaults
Provides more reliable cross-browser consistency
Use Case
Used for unique designs with full control
Used for maintaining consistency with minimal effort
Is it important to test the webpage in different browsers?
Yes, testing web pages in different browsers is essential to ensure:
Cross-browser compatibility.
A consistent user experience.
Accessibility for all users, regardless of their browser choice.
What are CSS HSL colours?
HSL stands for Hue, Saturation, Lightness:
Hue: Defines the colour, measured in degrees (0-360).
Saturation: Controls the intensity, from 0% (grey) to 100% (full colour).
Lightness: Adjusts brightness, from 0% (black) to 100% (white).
Example:
/* Light blue colour */
color: hsl(200, 100%, 50%);
What are pseudo-elements and pseudo-classes?
Pseudo-elements: Are used to select parts of an element like ::before and ::after
Pseudo-classes: Select elements depending on their state e.g. :hover , :first-child
Does margin-top or margin-bottom affect inline elements?
No, margin-top and margin-bottom do not affect inline elements. Margins on inline elements (like span or a) only work for the horizontal (margin-left and margin-right) sides.
What are CSS backgrounds, and what are their properties?
CSS background properties allow control over the background of elements:
background-color: Sets the background colour.
background-image: Sets the background image.
background-repeat: Defines if/how the background image repeats.
background-position: Positions the background image.
background-size: Specifies the size of the background image.
What is the difference between inline, inline block, and block?
Property
inline
inline-block
block
Default Width
Shrinks to fit content
Shrinks to fit content
Expands to fill the container width
Allows Width/Height
No
Yes
Yes
Line Break
No
No
Yes
Display Behaviour
Flows within text
Flows within text but maintains block properties
Stacked on top of each other
What is cascading in CSS?
Cascading refers to the way CSS styles are applied to elements based on:
Source Order: Later styles override earlier ones.
Specificity: More specific selectors override less specific ones.
Inheritance: Some properties are inherited from parent elements.
What are the different CSS border properties?
Different CSS border properties include :
border-width: Sets the width of the border.
border-style: Specifies whether it should be dashed, solid or dotted among other options.
border-color: Determines the colour of the border.
border-radius: Rounds off edges of borders.
What is the difference between margin and padding?
Property
Margin
Padding
Purpose
Creates space outside the element’s border
Creates space inside the element’s border
Affects Background
No
Yes
Collapsing
Can collapse with adjacent element’s margin
Does not collapse
Which property is used for changing the font face?
The font-family property is used to change the font face of an element.
Example:
p {
font-family: Arial, sans-serif;
}
What does margin: 40px 100px 120px 80px signify?
This shorthand sets all four margins:
Top margin: 40px
Right margin: 100px
Bottom margin: 120px
Left margin: 80px
What are the differences between adaptive design and responsive design?
Property
Adaptive Design
Responsive Design
Approach
Uses fixed layouts for different screen sizes
Uses flexible, fluid grids
Flexibility
Less flexible
Highly flexible and fluid
Media Queries
Often uses specific breakpoints
Uses relative units and fluid breakpoints
How does the browser match CSS selectors against elements?
Browsers match CSS selectors against elements using a process called Selector Matching:
Starts from the rightmost selector and moves left.
Checks each element in the document tree to find matches.
Applies the styles once a match is found.
How is border-box different from content-box?
Property
border-box
content-box
Box Model Calculation
Includes padding and border in width/height
Only includes content in width/height
Usage
More predictable layout control
Traditional CSS box model
How is opacity specified in CSS3?
Opacity in CSS3 is specified using the opacity property. It ranges from 0 (completely transparent) to 1 (fully opaque).
Example:
/* 50% transparent */
.element {
opacity: 0.5;
}
Why should we use the float property in CSS?
The float property is used for:
Aligning elements to the left or right within their container.
Creating text wraps around images or other elements.
Designing simple column layouts before Flexbox and Grid were widely supported.
What is z-index, and how does it function?
Overlapping elements can be managed using z-index. An element that has a higher z-index will appear on top of an element with a lower z-index. It only applies to positioned elements (i.e.relative, absolute, fixed or sticky).
How can we format text in CSS?
CSS provides several properties to format text:
colour: Sets the text colour.
font-size: Defines the size of the text.
font-weight: Specifies the thickness (boldness).
text-align: Aligns text (left, right, centre, justify).
text-decoration: Adds decorations like underline, overline, and line-through.
What is the difference between CSS border and outline?
Property
Border
Outline
Affects Layout
Yes
No, does not affect layout
Can be Rounded
Yes
No, cannot be rounded
Default Position
Inside the element’s box
Drawn outside the element’s border
Inherited
No
No
What do the following CSS selectors mean?
* (Universal Selector): Selects all elements.
div (Element Selector): Selects all <div> elements.
.className (Class Selector): Selects elements with the class “className”.
#idName (ID Selector): Select the element with the ID “idName”.
[type=”text”] (Attribute Selector): Selects elements with a type attribute value of “text”.
What are the properties of Flexbox?
The Flexbox properties include:
display: flex or inline-flex /This defines a flex container.
flex-direction: This establishes the direction of flex items (row, column).
justify-content: It helps align items horizontally (start, end, centre, space-between).
align-items: This helps align things vertically (start, end, centre, stretch).
flex-wrap: In case one wants to allow the wrapping of items across multiple lines then set this flex-wrap attribute as wrap.
What is the difference between display: none and visibility: hidden?
Property
display: none
visibility: hidden
Removes Element
Yes, element is removed from the document flow
No, element remains in the document flow
Space Occupied
No
Yes
Affects Layout
Yes
No
Can Be Clicked
No
No
What are the different CSS link states?
CSS defines four link states:
a:link: Unvisited link.
a:visited: Visited link.
a:hover: Link when hovered over by the mouse.
a:active: Link when it is being clicked.
How can we hide an element in CSS?
An element can be hidden using:
display: none: Removes the element from the document flow.
visibility: hidden: Hides the element but keeps its space.
opacity: 0: Makes the element fully transparent but interactive.
Can we overlap elements in CSS?
Yes, elements can overlap using:
position: absolute, relative, or fixed to position elements.
z-index to control the stacking order of overlapping elements.
What are the various positioning properties in CSS?
CSS positioning properties include:
static: Default positioning; elements are placed in the document flow.
relative: Positioned relative to its normal position.
absolute: Positioned relative to its nearest positioned ancestor.
fixed: Positioned relative to the browser window.
sticky: Toggles between relative and fixed based on the scroll position.
Compare different display values and explain their effects.
Property
display: block
display: inline
display: inline-block
display: flex
display: grid
Default Width
Expands to fill the container width
Shrinks to fit content
Shrinks to fit content
Expands or shrinks based on container
Creates a grid-based layout
Allows Width/Height
Yes
No
Yes
Yes
Yes
Line Break
Yes
No
No
No
No
Display Behaviour
Stacked on top of each other
Flows within text
Flows within text but maintains block properties
Container for flex items
Container for grid items
List common pseudo-classes in CSS and describe their uses.
Common Pseudo-Classes:
:hover: Applies styles when the user hovers over an element.
:focus: Applies styles when an element, like a form input, gains focus.
:first-child: Targets the first child of its parent.
:last-child: Targets the last child of its parent.
:nth-child(n): Targets the nth child of its parent.
:disabled: Applies styles to disabled form elements.
Highlight the differences between CSS Grid and Flexbox.
Feature
CSS Grid
Flexbox
Layout Type
Two-dimensional layout (rows and columns)
One-dimensional layout (row or column)
Use Cases
Complex layouts with both rows and columns
Simple layouts focusing on either rows or columns
Item Alignment
Can control horizontal and vertical simultaneously
Aligns items in one direction at a time
Alignment Methods
grid-template-rows, grid-template-columns
justify-content, align-items, align-content
Describe various types of CSS selectors, such as element, class, ID, attribute, and pseudo-class selectors.
Types of CSS Selectors:
Element Selector (div, p): Targets all elements of a specific type.
Class Selector (.className): Targets elements with a specific class.
ID Selector (#idName): Targets a unique element with a specific ID.
Attribute Selector ([type=”text”]): Targets elements with a specific attribute.
Pseudo-Class Selector (:hover, :focus): Targets elements based on their state or position.
List common media query breakpoints used in responsive design, including pixel values for mobile, tablet, and desktop.
Common Media Query Breakpoints:
Mobile: Up to 480px (@media (max-width: 480px))
Tablet: 481px to 768px (@media (min-width: 481px) and (max-width: 768px))
Desktop: 769px to 1024px (@media (min-width: 769px) and (max-width: 1024px))
Large Desktop: 1025px and above (@media (min-width: 1025px))
Describe various CSS animation properties.
CSS Animation Properties:
animation-name: Specifies the name of the keyframe to use.
animation-duration: Defines how long the animation lasts (e.g., 2s).
animation-timing-function: Specifies the speed curve (e.g., ease, linear).
animation-delay: Sets a delay before the animation starts.
animation-iteration-count: Number of times the animation repeats.
Compare different CSS colour formats, including hex, rgb, rgba, hsl, and hsla.
Format
Description
Example
hex
Hexadecimal code for colour values.
#FF5733
rgb
Defines colours using Red, Green, and Blue values.
rgb(255, 87, 51)
rgba
RGB with Alpha (opacity) value.
rgba(255, 87, 51, 0.5)
hsl
Hue, Saturation, Lightness.
hsl(9, 100%, 60%)
hsla
HSL with Alpha (opacity) value.
hsla(9, 100%, 60%, 0.5)
Describe the different alignment properties used in Flexbox, such as align-items, align-self, and justify-content.
Property
Description
Values
align-items
Aligns flex items along the cross axis (vertical).
flex-start, flex-end, centre, baseline, stretch
align-self
Aligns a single flex item differently than the others.
Same values as align-items
justify-content
Aligns flex items along the main axis (horizontal).
flex-start, flex-end, centre, space-between, space-around
Explain different CSS font properties.
CSS Font Properties:
font-family: Defines the font type (e.g., Arial, sans-serif).
font-size: Sets the font size (e.g., 16px, 1em).
font-weight: Specifies the font’s thickness (e.g., normal, bold, 100, 700).
font-style: Applies styles like italics (e.g., normal, italic).
line-height: Sets the space between lines of text.
List different CSS animation timing functions.
CSS Animation Timing Functions:
ease: Starts slow, accelerates, and then slows down.
linear: Constant speed from start to finish.
ease-in: Starts slow and accelerates towards the end.
ease-out: Starts fast and decelerates towards the end.
What is the difference between CSS Grid and Flexbox?
Feature
CSS Grid
Flexbox
Layout Type
Two-dimensional (rows and columns)
One-dimensional (row or column)
Use Case
Complex layouts involving both rows and columns
Simple layouts focusing on a single axis
Item Control
Precise control over both rows and columns simultaneously
Controls alignment of items on one axis
Browser Support
Supported in modern browsers
Supported in modern browsers
What does the CSS float property do?
The float property in CSS moves an element to the left or right, allowing text and inline elements to wrap around it. It is often used for creating simple layouts, like text wrapping around images or sidebars, before the advent of Flexbox and Grid.
What does display: inline-block do?
display: inline-block allows an element to behave like an inline element while retaining the ability to set its width and height, similar to a block element. Elements appear on the same line but can have padding, margins, and other block-level properties.
Write CSS code to create a sticky header that stays fixed at the top when scrolling.
header {
position: sticky;
top: 0; /* Sticks at the top */
background-color: #ffffff;
padding: 10px;
z-index: 1000; /* Ensures it stays on top */
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}
How can you use CSS to control image repetition?
CSS controls image repetition using the background-repeat property. Options include:
repeat: Repeats the image both horizontally and vertically.
repeat-x: Repeats the image only horizontally.
repeat-y: Repeats the image only vertically.
no-repeat: Does not repeat the image.
Example:
/* No repetition */
background-image: url('image.png');
background-repeat: no-repeat;
How do you centre align a div inside another div?
To centre a div horizontally and vertically, use Flexbox:
print: Targets print preview and printed documents.
screen: Targets computer screens, tablets, smartphones, etc.
speech: Targets screen readers and other speech-based devices.
What is the grid system in CSS?
The CSS Grid system is a layout method that provides a two-dimensional grid-based structure. It allows for the creation of complex layouts with rows and columns. The grid system uses properties like grid-template-rows, grid-template-columns, and grid-gap to control the layout of grid items.
How does calc() work in CSS?
calc() allows for dynamic calculations of CSS property values. It supports addition (+), subtraction (-), multiplication (*), and division (/) to combine units like px, %, em, and rem.
Describe different position values in CSS and their effects on elements.
Position Value
Description
Effects on Elements
static
Default positioning; elements are positioned according to the normal flow.
No special positioning; the element flows normally with the page.
relative
Positioned relative to its normal position.
Can be moved using top, bottom, left, and right properties; affects the positioning of its children.
absolute
Positioned relative to the nearest positioned ancestor.
Removed from the normal document flow; can overlap other elements.
fixed
Positioned relative to the browser window.
Stays fixed at a specific position on the screen, even when scrolling.
sticky
Toggles between relative and fixed based on scroll position.
Behaves like a relative until a certain scroll point, then becomes fixed.
What are pseudo-classes in CSS?
Pseudo-classes are keywords added to selectors to target elements based on their state or characteristics, such as:
:hover: Applies styles when the user hovers over an element.
:focus: Applies styles when an element gains focus (e.g., input fields).
:first-child: Targets the first child of a parent.
How can we centre an image in CSS?
To centre an image horizontally in a container, use the following CSS:
/* Centre image */
.container {
text-align: centre; /* Centres inline elements like images */
}
img {
display: block; /* Treats the image as a block element */
margin: 0 auto; /* Auto margins centre the image */
}
What does !important mean in CSS?
!important is used to give a CSS rule the highest priority, overriding other conflicting styles, regardless of specificity. It should be used sparingly as it makes debugging and maintenance difficult.
Example:
p {
color: red !important; /* This will override other colour rules for <p> elements */
}
How can we vertically centre text in CSS?
To vertically centre text within a container, you can use Flexbox or line-height:
Using Flexbox:
.container {
display: flex;
align-items: center; /* Centres text vertically */
justify-content: center; /* Centres text horizontally */
height: 200px; /* Example height */
}
<strong>Using Line Height:</strong>
.container {
height: 200px;
line-height: 200px; /* Matches container height */
text-align: center; /* Centres text horizontally */
}
What is specificity, and how do you calculate it?
Specificity determines which CSS rule is applied to an element. It is calculated based on the types of selectors used:
Selector Type
Points Assigned
Inline styles
1000
ID selectors (#id)
100
Class selectors (.class), attribute selectors, pseudo-classes
10
Type selectors (div), pseudo-elements (::before)
1
Calculate specificity by adding points for each type of selector in the rule.
What are the advantages of using translate() instead of absolute positioning?
Advantages of using translate():
GPU Acceleration: translate() triggers GPU acceleration, making animations smoother.
Better Performance: This does not affect the document flow, improving performance.
Retains Element’s Flow: Keeps the element in its original position in the DOM, avoiding reflows.
How do you determine if a browser supports a certain feature?
To check browser support:
Use @supports Rule: Apply styles based on feature support.
@supports (display: grid) {
/* Grid-specific styles */
}
How do you fix browser-specific styling issues?
To fix browser-specific issues:
Use Vendor Prefixes: Add browser-specific prefixes (e.g., -webkit-, -moz-).
Conditional Comments: Use conditionals to target specific browsers.
Reset/Normalize CSS: Use a reset or normalise stylesheet to standardise styles across browsers.
Feature Detection: Use JavaScript libraries like Modernizr to detect and apply fallbacks.
Compare different CSS units such as px, em, rem, %, vw, and vh, and explain when to use them.
Unit
Description
When to Use
px
Pixels; absolute unit.
Use for fixed sizes, like borders or specific element dimensions.
em
Relative to the font size of the parent element.
Use for scalable typography and elements that should scale with their parent.
rem
Relative to the root element’s font size.
Use for consistent scaling across the document, unaffected by parent elements.
%
Percentage; relative to the parent element’s size.
Use for responsive designs where sizes need to adjust relative to the parent element.
vw
Viewport width; 1vw is 1% of the viewport width.
Use for responsive widths that scale with the entire viewport size.
vh
Viewport height; 1vh is 1% of the viewport height.
Use for responsive heights that scale with the entire viewport size.
How does the overflow: hidden property work?
overflow: hidden hides any content that exceeds the element’s defined width or height. It prevents scrolling and clipping of content beyond the element’s boundaries. It is often used for creating custom scrollbars or managing layouts.
Write CSS to create a full-width image slider that cycles through images every 3 seconds.
These combine multiple images into one file so as to reduce the number of HTTP requests made on a page, thus making it faster in terms of loading. They are commonly used for small images like icons or buttons.
What do you understand by tweening in CSS?
Tweening (a short form of “in-betweening”) is creating intermediate frames or states within CSS animations. It requires using @keyframes to determine how properties such as position, size or colour change over time.
Example:
@keyframes slide {
from { transform: translateX(0); }
to { transform: translateX(100px); }
}
Why do we need to use the clear property along with floats in CSS?
The clear property is used to avoid wrapping around floated elements. It forces elements to move below any preceding floated elements, maintaining the layout’s integrity. It is commonly used to clear floats and fix issues where parent containers do not stretch to the full height of floated elements.
How does absolute positioning work in CSS?
Absolute positioning removes an element from the normal document flow and positions it relative to its nearest positioned ancestor (an element with relative, absolute, fixed, or sticky positioning). If no ancestor is positioned, it defaults to the body element.
What is CSS overflow?
overflow controls what happens when content exceeds the size of its container. Options include:
visible: Content is not clipped and may overflow the element’s box.
hidden: Content is clipped, and the rest is hidden.
scroll: Content is clipped, but scrollbars are added to view the rest.
auto: Scrollbars are added only if necessary.
How do you implement a flexbox-based card layout with evenly spaced cards? Provide a code example.
.container {
display: flex;
flex-wrap: wrap;
gap: 20px; /* Space between cards */
justify-content: space-evenly; /* Even spacing between cards */
}
.card {
background-color: #f4f4f4;
width: calc(33.33% - 20px); /* Responsive width with gap considered */
padding: 20px;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}
List and explain various Flexbox properties like justify-content, align-items, flex-direction, and flex-wrap.
Property
Description
Values
justify-content
Aligns items horizontally within the flex container
flex-start, flex-end, centre, space-between, space-around
align-items
Aligns items vertically within the flex container
flex-start, flex-end, centre, baseline, stretch
flex-direction
Defines the direction of the flex items
row, row-reverse, column, column-reverse
flex-wrap
Allows flex items to wrap onto multiple lines
nowrap, wrap, wrap-reverse
Write CSS to create a centred modal popup that appears when a button is clicked.
.modal {
display: none; /* Hidden by default */
position: fixed;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
width: 300px;
background-color: white;
padding: 20px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
z-index: 1001;
}
.modal.active {
display: block; /* Shown when active class is added */
}
Write CSS to create a responsive form layout that adapts to different screen sizes.
form {
display: flex;
flex-wrap: wrap;
gap: 20px; /* Space between form elements */
}
input[type="text"], input[type="email"], input[type="password"], textarea {
flex: 1 1 100%; /* Full width on smaller screens */
min-width: 200px;
padding: 10px;
margin-bottom: 10px;
border: 1px solid #ddd;
}
@media (min-width: 768px) {
input[type="text"], input[type="email"], input[type="password"] {
flex: 1 1 calc(50% - 20px); /* Half width on larger screens */
}
}
CSS is very important for web development because it provides a way for configuring and positioning web pages, which can easily attract users. Understanding CSS principles and basic rules such as Grid, Flexbox, Selectors and Animations is very important for any web developer. These principles are of the utmost importance to any web designer or front-end developer who is keen on creating aesthetically appealing, modern, and responsive web applications.
The purpose of this blog is to present various types of CSS interview questions and their answers, beginning with the easy one and ending with the tough one. In this way, you will get enough preparation to polish your CSS skills and so well handle interviews. Keep practising such CSS so that you remain relevant to all the current trends of CSS and further enhance your skills in web development.
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.