Top 30+ CSS Interview Questions and Answers

Table of Contents

CSS (Cascading Style Sheets) is a cornerstone technology used in web development to style HTML content. Whether you’re a fresher or an experienced developer, preparing for CSS interview questions is crucial to showcase your understanding of web design and front-end development. In this article, we’ll explore common CSS interview questions tailored for freshers and experienced professionals.

CSS Interview Questions for Freshers

1. What is CSS?

CSS stands for Cascading Style Sheets. It’s a stylesheet language used to describe the look and formatting of a document written in HTML or XML. Think of it as the design layer of your web pages, dictating how elements should appear on the screen, in print, or on other media.

2. What is the difference between class selectors and ID selectors in CSS?

Class selectors are defined with a period (.) followed by the class name, while ID selectors are defined with a hash (#) followed by the ID name. The key difference is that classes can be reused multiple times on a page, whereas IDs must be unique within the page.

3. What are CSS pseudo-classes?

Pseudo-classes are keywords added to selectors that specify a special state of the selected elements. For example, :hover can be used to change the style of an element when the mouse hovers over it.

4. How do you center a div horizontally and vertically?

To center a div horizontally and vertically, you can use Flexbox or CSS Grid. Here’s how you can do it with Flexbox:

				
					.container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}
.content {
  width: 50%;
  height: 50%;
}
				
			

This code snippet creates a container that centers its content both horizontally and vertically.

5. What is the box model in CSS?

The CSS Box Model is quite important in web development because it performs a critical position in designing and laying out internet pages. Essentially, it treats each HTML detail as a box, no matter whether it is textual content or a simple photograph. The Box Model defines this imaginary box and specifies the space that the element occupies on a web page. Let’s break down its components:

CSS Interview Questions (CSS Box )Model
  1. Content: At the center of the field is the Content, in which the real content material (textual content, photo, and so forth.) is living. This is wherein developers have the capacity to manipulate the scale using properties like width and height, shaping the detail to in shape the layout.
  2. Padding: Padding is the gap among the content material and the border. It acts as cushioning around the content material, ensuring that the content doesn’t touch the border directly. Properties like padding-pinnacle, padding-right, padding-bottom, and padding-left can be used to adjust the padding.
  3. Border: The border wraps across the padding (or the content if there may be no padding). It’s the seen line (or container) that surrounds the detail. Properties like border-width, border-style, and border-color may be used to outline the width, fashion (strong, dashed, dotted, and many others.), and shade of the border.
  4. Margin: The margin is the outermost layer, developing space between the detail’s border and neighboring factors. It ensures that elements do not stick too near each other. Properties like margin-pinnacle, margin-proper, margin-backside, and margin-left may be used to adjust the margins.

6. Explain the difference between padding and margin.

Padding is the space between the content and the border of an element, while margin is the space outside the border of an element. Padding affects the element’s size, but margin does not.

7. What are media queries?

Media queries are used in responsive design to apply different styles for different devices or screen sizes. They use the @media rule to include a block of CSS properties only if a certain condition is true, such as a screen width.

8. How can you apply a CSS style to a specific element with a particular attribute?

You can use attribute selectors. For example

				
					input[type="text"] {
  background-color: lightblue;
}
				
			

This selector targets all input elements with a type attribute of "text".

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

Difference between Inline, Block and Inline Block Elements in CSS
Property Inline Elements Block Elements Inline-Block Elements
Default Behavior
Flows within the content, does not start on a new line.
Starts on a new line and takes up the full width available.
Flows within the content but respects width and height properties.
Examples
span, a, img, strong, em
div, p, h1 to h6, section, article
button, input, img (when styled)
Width and Height
Cannot set width and height.
Can set width and height.
Can set width and height.
Padding and Margin
Applies only horizontally.
Applies both horizontally and vertically.
Applies both horizontally and vertically.
Line Breaks
Does not force a line break.
Forces a line break before and after the element.
Does not force a line break.
Box Model
Width and height are not respected; padding and margins affect only the left and right.
Width, height, padding, and margin are all respected.
Width, height, padding, and margin are all respected.
Display Property
display: inline;
display: block;
display: inline-block;
Use Case
Used for styling parts of text or images.
Used for structuring the layout of the page.
Used when you need block-level behavior but within inline flow.

10. How do you include a CSS file in an HTML document?

You include a CSS file using the <link> tag within the <head> section of the HTML document:

<link rel=”stylesheet” type=”text/css” href=”styles.css”>

11. What are CSS preprocessors? Name a few.

CSS preprocessors are scripting languages that extend CSS and compile it into regular CSS. Examples include Sass, LESS, and Stylus.

12. Explain the concept of specificity in CSS.

Specificity determines which CSS rule is applied by the browser when multiple rules could apply to the same element. Specificity is calculated based on the number and type of selectors used. For example, IDs have higher specificity than classes, which have higher specificity than elements.

13. How do you use Flexbox to create a responsive layout?

Flexbox is a layout model that allows you to design a responsive layout easily. For example:

CSS Flexbox
				
					<div class="flex-container">
  <div class="flex-item">1</div>
  <div class="flex-item">2</div>
  <div class="flex-item">3</div>
</div>
				
			
				
					.flex-container {
  display: flex;
  flex-direction: row; /* Default value */
  justify-content: center; /* Center flex items horizontally */
  align-items: center; /* Center flex items vertically */
  height: 100vh; /* Full viewport height */
}
.flex-item {
  background-color: lightcoral;
  padding: 20px;
  margin: 10px;
  color: white;
  font-size: 2rem;
}
				
			

14. What is the purpose of the z-index property in CSS?

The z-index property specifies the stack order of an element. An element with a higher z-index is always in front of an element with a lower z-index.

15. How do you create a simple CSS animation?

You can create a CSS animation using @keyframes and the animation property:

				
					@keyframes example {
  from {background-color: red;}
  to {background-color: yellow;}
}
.animate {
  animation: example 5s infinite;
}
				
			

This will create an animation that changes the background color of an element from red to yellow over 5 seconds and repeats indefinitely.

CSS Interview Questions for Experienced

1. What is the difference between relative, absolute, fixed, and sticky positioning in CSS?

Relative positions an element relative to its normal position. absolute positions an element relative to its nearest positioned ancestor. fixed positions of an element relative to the viewport. sticky toggles between relative and fixed based on scroll position.

Below is the tabular format where you can understand better.

Positioning Type Description Position Relative To Effect on Document Flow
Relative
Position an element relative to its normal position.
Its normal position in the document flow.
Element remains in the document flow.
Absolute
Position an element relative to its nearest positioned ancestor or the initial containing block if none.
The nearest positioned ancestor or initial containing block.
Element is removed from the document flow.
Fixed
Position an element relative to the viewport; it stays in place when the page is scrolled.
The viewport.
Element is removed from the document flow.
Sticky
Toggles between relative and fixed positioning based on scroll position.
Its nearest scrolling ancestor.
Element remains in the document flow until it becomes fixed.

2. How do you optimize CSS for better performance?

Optimize CSS by minimizing and compressing files, using CSS sprites, avoiding complex selectors, and reducing the use of expensive properties like box-shadow.

3. What are CSS variables and how do you use them?

CSS variables, also known as custom properties, allow you to store values that you can reuse throughout your stylesheet. Example:

				
					:root {
  --primary-color: #3498db;
}
.header {
  color: var(--primary-color);
}
				
			

4. Explain the concept of CSS Grid and provide an example.

CSS Grid Layout, commonly referred to as CSS Grid, is a two-dimensional layout system for the web. It provides a powerful way to design complex, responsive web layouts. With CSS Grid, you can control both the rows and columns of your layout, making it easier to create grid-based designs.

				
					.container {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-gap: 10px;
}
.item {
  background-color: lightcoral;
}
				
			
CSS Interview Questions (CSS Grid)

Properties for the Grid Container

  • display: grid; or display: inline-grid;: Defines the container as a grid container.
  • grid-template-columns: Defines the number and size of columns in the grid.
  • grid-template-rows: Defines the number and size of rows in the grid.
  • grid-template-areas: Defines named grid areas.
  • gap (or grid-gap): Defines the space between rows and columns.
  • justify-items: Aligns grid items along the row axis.
  • align-items: Aligns grid items along the column axis.

Properties for the Grid Items

  • grid-column-start, grid-column-end: Define where a grid item starts and ends on the column axis.
  • grid-row-start, grid-row-end: Define where a grid item starts and ends on the row axis.
  • grid-area: Assigns a grid item to a named grid area.
  • justify-self: Aligns a grid item along the row axis within its grid cell.
  • align-self: Aligns a grid item along the column axis within its grid cell.

5. How do you create a CSS transition?

CSS transitions allow you to change property values smoothly over a given duration. Example:

				
					.box {
  width: 100px;
  height: 100px;
  background-color: blue;
  transition: background-color 0.5s ease;
}
.box:hover {
  background-color: green;
}
				
			

6. What is the difference between em and rem units in CSS?

em units are relative to the font-size of the parent element, while rem units are relative to the root element’s font-size.

Unit Description Relative To Common Use Cases
em
Relative unit that scales based on the font size of the parent element.
Font size of the parent element.
Nested elements, scaling based on container font size.
rem
Relative unit that scales based on the font size of the root element (usually the html element).
Font size of the root element.
Consistent, global sizing across the entire document.

em Unit Calculation:

If the parent element has a font-size of 16px and an element within it has a width of 2em, then the width of that element is 2 * 16px = 32px.

rem Unit Calculation:

If the root element (<html>) has a font-size of 16px and an element has a width of 2rem, then the width of that element is 2 * 16px = 32px.

7. How do you use CSS to hide an element but keep it in the document flow?

To hide an element but keep it in the document flow, you can use the visibility: hidden; CSS property. This property makes the element invisible while still occupying space in the layout.

When to Use visibility: hidden;

  • Maintaining Layout: When you want to hide an element but keep its allocated space to maintain the overall layout structure.
  • Temporarily Hiding Elements: When you need to hide elements temporarily without causing layout shifts or reflows.
  • Interactive Content: In cases where the hidden element might need to be shown again based on user interaction or some condition, and you want to avoid layout changes when toggling visibility.

8. What is Block Element Modifier (BEM) and how is it used in CSS?

BEM is a naming convention for classes in HTML and CSS to create reusable components. Example:

.block {}
.block__element {}
.block–modifier {}

9. Explain the concept of CSS specificity hierarchy.

CSS specificity hierarchy is a method for determining which CSS rule will be applied to an element. It is based on the number of IDs, classes, and element selectors in a rule.

10. How do you implement a CSS reset?

A CSS reset is used to remove default browser styling. You can use a popular reset stylesheet like Normalize.css or create your own reset rules.

11. What are CSS counters and how do you use them?

CSS counters are used to add a counter to an element and increment it in other elements. Example:

CSS Counters
				
					/* Initialize the counter for sections and subsections */
body {
  counter-reset: section;
}

section {
  counter-reset: subsection; /* Reset subsection counter for each section */
}

h2::before {
  counter-increment: section; /* Increment section counter */
  content: "Section " counter(section) ": "; /* Display section counter */
}

.subsection h3::before {
  counter-increment: subsection; /* Increment subsection counter */
  content: counter(section) "." counter(subsection) " "; /* Display section and subsection counter */
}

p::before {
  content: counter(section) "." counter(subsection) "." counter(p) " "; /* Display nested counters */
}
				
			

Key Concepts of CSS Counters:

  • Counter Initialization: Use the counter-reset property to create or reset a counter.
  • Counter Increment: Use the counter-increment property to increment the counter value.
  • Counter Display: Use the content property in combination with the counter() or counters() functions to display the counter.

12. Explain the will-change property in CSS.

The will-change property hints to the browser that an element will undergo changes. This allows the browser to optimize performance by preparing the element for changes.

Key Points About will-change:

(i) Purpose: The primary goal of will-change is to let the browser know which elements will undergo changes, so it can prepare for these changes in advance, which can also help in avoiding performance issues.

(ii) Syntax:

element {
 will-change: property;
}

property: The name of the CSS property that is expected to change. Commonly used properties include transform, opacity, top, left, etc. You can specify multiple properties separated by a comma:

element {
 will-change: transform, opacity;
}

(iii) Common Use Cases:

  • Animations: When you have elements that will be animated, especially with properties like transform or opacity.
  • Transitions: When elements will transition between states and you want to ensure smoothness.
  • Dynamic Content: When you have interactive elements that change based on user input.

13. How do you create a responsive web design using CSS?

Use responsive techniques like fluid grids, flexible images, and media queries to create layouts that adapt to different screen sizes.

14. What is the difference between display: none; and visibility: hidden;?

Property display: none; visibility: hidden;
Visibility
Completely removes the element from the layout
Hides the element but keeps it in the layout.
Space
The element does not take up any space.
The element still takes up space.
Document Flow
Removed from the document flow.
Remains in the document flow.
Interactivity
The element and its content are not interactive.
The element is hidden, but its space is still interactive.
Re-rendering
The element is re-rendered if made visible again.
No re-rendering required when made visible again.
Use Cases
When you want to completely hide an element and not affect the layout.
When you want to hide an element but maintain the layout structure.

Visual Example:

Imagine you have three boxes side by side. Here’s how display: none; and visibility: hidden; affect their layout:

				
					<div class="box box1">Box 1</div>
<div class="box box2">Box 2</div>
<div class="box box3">Box 3</div>
				
			
				
					.box {
  width: 100px;
  height: 100px;
  margin: 10px;
  display: inline-block;
  background-color: lightblue;
  text-align: center;
  line-height: 100px;
}
.hidden-display {
  display: none;
}
.hidden-visibility {
  visibility: hidden;
}
				
			
Display None and Visibility Hidden

15. How do you use CSS to create a sticky footer?

When a sticky footer is created using CSS, it stays at the bottom of the viewport for short content and moves down to make room for more content on long form content. There are two methods to create a sticky footer in CSS.

Method 1: Using Flexbox

Flexbox is a great way to create a sticky footer with minimal code.

				
					<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Sticky Footer</title>
  
</head>
<body>
  <div class="container">
    <header class="header">
      Header
    </header>
    <main class="content">
      Main content goes here.
    </main>
    <footer class="footer">
      Sticky Footer
    </footer>
  </div> <script data-no-optimize="1">!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t="undefined"!=typeof globalThis?globalThis:t||self).LazyLoad=e()}(this,function(){"use strict";function e(){return(e=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var n,a=arguments[e];for(n in a)Object.prototype.hasOwnProperty.call(a,n)&&(t[n]=a[n])}return t}).apply(this,arguments)}function i(t){return e({},it,t)}function o(t,e){var n,a="LazyLoad::Initialized",i=new t(e);try{n=new CustomEvent(a,{detail:{instance:i}})}catch(t){(n=document.createEvent("CustomEvent")).initCustomEvent(a,!1,!1,{instance:i})}window.dispatchEvent(n)}function l(t,e){return t.getAttribute(gt+e)}function c(t){return l(t,bt)}function s(t,e){return function(t,e,n){e=gt+e;null!==n?t.setAttribute(e,n):t.removeAttribute(e)}(t,bt,e)}function r(t){return s(t,null),0}function u(t){return null===c(t)}function d(t){return c(t)===vt}function f(t,e,n,a){t&&(void 0===a?void 0===n?t(e):t(e,n):t(e,n,a))}function _(t,e){nt?t.classList.add(e):t.className+=(t.className?" ":"")+e}function v(t,e){nt?t.classList.remove(e):t.className=t.className.replace(new RegExp("(^|\\s+)"+e+"(\\s+|$)")," ").replace(/^\s+/,"").replace(/\s+$/,"")}function g(t){return t.llTempImage}function b(t,e){!e||(e=e._observer)&&e.unobserve(t)}function p(t,e){t&&(t.loadingCount+=e)}function h(t,e){t&&(t.toLoadCount=e)}function n(t){for(var e,n=[],a=0;e=t.children[a];a+=1)"SOURCE"===e.tagName&&n.push(e);return n}function m(t,e){(t=t.parentNode)&&"PICTURE"===t.tagName&&n(t).forEach(e)}function a(t,e){n(t).forEach(e)}function E(t){return!!t[st]}function I(t){return t[st]}function y(t){return delete t[st]}function A(e,t){var n;E(e)||(n={},t.forEach(function(t){n[t]=e.getAttribute(t)}),e[st]=n)}function k(a,t){var i;E(a)&&(i=I(a),t.forEach(function(t){var e,n;e=a,(t=i[n=t])?e.setAttribute(n,t):e.removeAttribute(n)}))}function L(t,e,n){_(t,e.class_loading),s(t,ut),n&&(p(n,1),f(e.callback_loading,t,n))}function w(t,e,n){n&&t.setAttribute(e,n)}function x(t,e){w(t,ct,l(t,e.data_sizes)),w(t,rt,l(t,e.data_srcset)),w(t,ot,l(t,e.data_src))}function O(t,e,n){var a=l(t,e.data_bg_multi),i=l(t,e.data_bg_multi_hidpi);(a=at&&i?i:a)&&(t.style.backgroundImage=a,n=n,_(t=t,(e=e).class_applied),s(t,ft),n&&(e.unobserve_completed&&b(t,e),f(e.callback_applied,t,n)))}function N(t,e){!e||0<e.loadingCount||0<e.toLoadCount||f(t.callback_finish,e)}function C(t,e,n){t.addEventListener(e,n),t.llEvLisnrs[e]=n}function M(t){return!!t.llEvLisnrs}function z(t){if(M(t)){var e,n,a=t.llEvLisnrs;for(e in a){var i=a[e];n=e,i=i,t.removeEventListener(n,i)}delete t.llEvLisnrs}}function R(t,e,n){var a;delete t.llTempImage,p(n,-1),(a=n)&&--a.toLoadCount,v(t,e.class_loading),e.unobserve_completed&&b(t,n)}function T(o,r,c){var l=g(o)||o;M(l)||function(t,e,n){M(t)||(t.llEvLisnrs={});var a="VIDEO"===t.tagName?"loadeddata":"load";C(t,a,e),C(t,"error",n)}(l,function(t){var e,n,a,i;n=r,a=c,i=d(e=o),R(e,n,a),_(e,n.class_loaded),s(e,dt),f(n.callback_loaded,e,a),i||N(n,a),z(l)},function(t){var e,n,a,i;n=r,a=c,i=d(e=o),R(e,n,a),_(e,n.class_error),s(e,_t),f(n.callback_error,e,a),i||N(n,a),z(l)})}function G(t,e,n){var a,i,o,r,c;t.llTempImage=document.createElement("IMG"),T(t,e,n),E(c=t)||(c[st]={backgroundImage:c.style.backgroundImage}),o=n,r=l(a=t,(i=e).data_bg),c=l(a,i.data_bg_hidpi),(r=at&&c?c:r)&&(a.style.backgroundImage='url("'.concat(r,'")'),g(a).setAttribute(ot,r),L(a,i,o)),O(t,e,n)}function D(t,e,n){var a;T(t,e,n),a=e,e=n,(t=It[(n=t).tagName])&&(t(n,a),L(n,a,e))}function V(t,e,n){var a;a=t,(-1<yt.indexOf(a.tagName)?D:G)(t,e,n)}function F(t,e,n){var a;t.setAttribute("loading","lazy"),T(t,e,n),a=e,(e=It[(n=t).tagName])&&e(n,a),s(t,vt)}function j(t){t.removeAttribute(ot),t.removeAttribute(rt),t.removeAttribute(ct)}function P(t){m(t,function(t){k(t,Et)}),k(t,Et)}function S(t){var e;(e=At[t.tagName])?e(t):E(e=t)&&(t=I(e),e.style.backgroundImage=t.backgroundImage)}function U(t,e){var n;S(t),n=e,u(e=t)||d(e)||(v(e,n.class_entered),v(e,n.class_exited),v(e,n.class_applied),v(e,n.class_loading),v(e,n.class_loaded),v(e,n.class_error)),r(t),y(t)}function $(t,e,n,a){var i;n.cancel_on_exit&&(c(t)!==ut||"IMG"===t.tagName&&(z(t),m(i=t,function(t){j(t)}),j(i),P(t),v(t,n.class_loading),p(a,-1),r(t),f(n.callback_cancel,t,e,a)))}function q(t,e,n,a){var i,o,r=(o=t,0<=pt.indexOf(c(o)));s(t,"entered"),_(t,n.class_entered),v(t,n.class_exited),i=t,o=a,n.unobserve_entered&&b(i,o),f(n.callback_enter,t,e,a),r||V(t,n,a)}function H(t){return t.use_native&&"loading"in HTMLImageElement.prototype}function B(t,i,o){t.forEach(function(t){return(a=t).isIntersecting||0<a.intersectionRatio?q(t.target,t,i,o):(e=t.target,n=t,a=i,t=o,void(u(e)||(_(e,a.class_exited),$(e,n,a,t),f(a.callback_exit,e,n,t))));var e,n,a})}function J(e,n){var t;et&&!H(e)&&(n._observer=new IntersectionObserver(function(t){B(t,e,n)},{root:(t=e).container===document?null:t.container,rootMargin:t.thresholds||t.threshold+"px"}))}function K(t){return Array.prototype.slice.call(t)}function Q(t){return t.container.querySelectorAll(t.elements_selector)}function W(t){return c(t)===_t}function X(t,e){return e=t||Q(e),K(e).filter(u)}function Y(e,t){var n;(n=Q(e),K(n).filter(W)).forEach(function(t){v(t,e.class_error),r(t)}),t.update()}function t(t,e){var n,a,t=i(t);this._settings=t,this.loadingCount=0,J(t,this),n=t,a=this,Z&&window.addEventListener("online",function(){Y(n,a)}),this.update(e)}var Z="undefined"!=typeof window,tt=Z&&!("onscroll"in window)||"undefined"!=typeof navigator&&/(gle|ing|ro)bot|crawl|spider/i.test(navigator.userAgent),et=Z&&"IntersectionObserver"in window,nt=Z&&"classList"in document.createElement("p"),at=Z&&1<window.devicePixelRatio,it={elements_selector:".lazy",container:tt||Z?document:null,threshold:300,thresholds:null,data_src:"src",data_srcset:"srcset",data_sizes:"sizes",data_bg:"bg",data_bg_hidpi:"bg-hidpi",data_bg_multi:"bg-multi",data_bg_multi_hidpi:"bg-multi-hidpi",data_poster:"poster",class_applied:"applied",class_loading:"litespeed-loading",class_loaded:"litespeed-loaded",class_error:"error",class_entered:"entered",class_exited:"exited",unobserve_completed:!0,unobserve_entered:!1,cancel_on_exit:!0,callback_enter:null,callback_exit:null,callback_applied:null,callback_loading:null,callback_loaded:null,callback_error:null,callback_finish:null,callback_cancel:null,use_native:!1},ot="src",rt="srcset",ct="sizes",lt="poster",st="llOriginalAttrs",ut="loading",dt="loaded",ft="applied",_t="error",vt="native",gt="data-",bt="ll-status",pt=[ut,dt,ft,_t],ht=[ot],mt=[ot,lt],Et=[ot,rt,ct],It={IMG:function(t,e){m(t,function(t){A(t,Et),x(t,e)}),A(t,Et),x(t,e)},IFRAME:function(t,e){A(t,ht),w(t,ot,l(t,e.data_src))},VIDEO:function(t,e){a(t,function(t){A(t,ht),w(t,ot,l(t,e.data_src))}),A(t,mt),w(t,lt,l(t,e.data_poster)),w(t,ot,l(t,e.data_src)),t.load()}},yt=["IMG","IFRAME","VIDEO"],At={IMG:P,IFRAME:function(t){k(t,ht)},VIDEO:function(t){a(t,function(t){k(t,ht)}),k(t,mt),t.load()}},kt=["IMG","IFRAME","VIDEO"];return t.prototype={update:function(t){var e,n,a,i=this._settings,o=X(t,i);{if(h(this,o.length),!tt&&et)return H(i)?(e=i,n=this,o.forEach(function(t){-1!==kt.indexOf(t.tagName)&&F(t,e,n)}),void h(n,0)):(t=this._observer,i=o,t.disconnect(),a=t,void i.forEach(function(t){a.observe(t)}));this.loadAll(o)}},destroy:function(){this._observer&&this._observer.disconnect(),Q(this._settings).forEach(function(t){y(t)}),delete this._observer,delete this._settings,delete this.loadingCount,delete this.toLoadCount},loadAll:function(t){var e=this,n=this._settings;X(t,n).forEach(function(t){b(t,e),V(t,n,e)})},restoreAll:function(){var e=this._settings;Q(e).forEach(function(t){U(t,e)})}},t.load=function(t,e){e=i(e);V(t,e)},t.resetStatus=function(t){r(t)},Z&&function(t,e){if(e)if(e.length)for(var n,a=0;n=e[a];a+=1)o(t,n);else o(t,e)}(t,window.lazyLoadOptions),t});!function(e,t){"use strict";function a(){t.body.classList.add("litespeed_lazyloaded")}function n(){console.log("[LiteSpeed] Start Lazy Load Images"),d=new LazyLoad({elements_selector:"[data-lazyloaded]",callback_finish:a}),o=function(){d.update()},e.MutationObserver&&new MutationObserver(o).observe(t.documentElement,{childList:!0,subtree:!0,attributes:!0})}var d,o;e.addEventListener?e.addEventListener("load",n,!1):e.attachEvent("onload",n)}(window,document);</script></body>
</html>
				
			
				
					html, body {
  height: 100%;
  margin: 0;
}
.container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
}
.header, .footer {
  background-color: #333;
  color: white;
  padding: 10px;
  text-align: center;
}
.content {
  flex: 1;
  padding: 20px;
}
				
			

Method 2: Using CSS Grid

CSS Grid can also be used to create a sticky footer, offering another approach to achieve the same layout.

				
					<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Sticky Footer</title>
  
</head>
<body>
  <div class="grid-container">
    <header class="header">
      Header
    </header>
    <main class="content">
      Main content goes here.
    </main>
    <footer class="footer">
      Sticky Footer
    </footer>
  </div> <script data-no-optimize="1">!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t="undefined"!=typeof globalThis?globalThis:t||self).LazyLoad=e()}(this,function(){"use strict";function e(){return(e=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var n,a=arguments[e];for(n in a)Object.prototype.hasOwnProperty.call(a,n)&&(t[n]=a[n])}return t}).apply(this,arguments)}function i(t){return e({},it,t)}function o(t,e){var n,a="LazyLoad::Initialized",i=new t(e);try{n=new CustomEvent(a,{detail:{instance:i}})}catch(t){(n=document.createEvent("CustomEvent")).initCustomEvent(a,!1,!1,{instance:i})}window.dispatchEvent(n)}function l(t,e){return t.getAttribute(gt+e)}function c(t){return l(t,bt)}function s(t,e){return function(t,e,n){e=gt+e;null!==n?t.setAttribute(e,n):t.removeAttribute(e)}(t,bt,e)}function r(t){return s(t,null),0}function u(t){return null===c(t)}function d(t){return c(t)===vt}function f(t,e,n,a){t&&(void 0===a?void 0===n?t(e):t(e,n):t(e,n,a))}function _(t,e){nt?t.classList.add(e):t.className+=(t.className?" ":"")+e}function v(t,e){nt?t.classList.remove(e):t.className=t.className.replace(new RegExp("(^|\\s+)"+e+"(\\s+|$)")," ").replace(/^\s+/,"").replace(/\s+$/,"")}function g(t){return t.llTempImage}function b(t,e){!e||(e=e._observer)&&e.unobserve(t)}function p(t,e){t&&(t.loadingCount+=e)}function h(t,e){t&&(t.toLoadCount=e)}function n(t){for(var e,n=[],a=0;e=t.children[a];a+=1)"SOURCE"===e.tagName&&n.push(e);return n}function m(t,e){(t=t.parentNode)&&"PICTURE"===t.tagName&&n(t).forEach(e)}function a(t,e){n(t).forEach(e)}function E(t){return!!t[st]}function I(t){return t[st]}function y(t){return delete t[st]}function A(e,t){var n;E(e)||(n={},t.forEach(function(t){n[t]=e.getAttribute(t)}),e[st]=n)}function k(a,t){var i;E(a)&&(i=I(a),t.forEach(function(t){var e,n;e=a,(t=i[n=t])?e.setAttribute(n,t):e.removeAttribute(n)}))}function L(t,e,n){_(t,e.class_loading),s(t,ut),n&&(p(n,1),f(e.callback_loading,t,n))}function w(t,e,n){n&&t.setAttribute(e,n)}function x(t,e){w(t,ct,l(t,e.data_sizes)),w(t,rt,l(t,e.data_srcset)),w(t,ot,l(t,e.data_src))}function O(t,e,n){var a=l(t,e.data_bg_multi),i=l(t,e.data_bg_multi_hidpi);(a=at&&i?i:a)&&(t.style.backgroundImage=a,n=n,_(t=t,(e=e).class_applied),s(t,ft),n&&(e.unobserve_completed&&b(t,e),f(e.callback_applied,t,n)))}function N(t,e){!e||0<e.loadingCount||0<e.toLoadCount||f(t.callback_finish,e)}function C(t,e,n){t.addEventListener(e,n),t.llEvLisnrs[e]=n}function M(t){return!!t.llEvLisnrs}function z(t){if(M(t)){var e,n,a=t.llEvLisnrs;for(e in a){var i=a[e];n=e,i=i,t.removeEventListener(n,i)}delete t.llEvLisnrs}}function R(t,e,n){var a;delete t.llTempImage,p(n,-1),(a=n)&&--a.toLoadCount,v(t,e.class_loading),e.unobserve_completed&&b(t,n)}function T(o,r,c){var l=g(o)||o;M(l)||function(t,e,n){M(t)||(t.llEvLisnrs={});var a="VIDEO"===t.tagName?"loadeddata":"load";C(t,a,e),C(t,"error",n)}(l,function(t){var e,n,a,i;n=r,a=c,i=d(e=o),R(e,n,a),_(e,n.class_loaded),s(e,dt),f(n.callback_loaded,e,a),i||N(n,a),z(l)},function(t){var e,n,a,i;n=r,a=c,i=d(e=o),R(e,n,a),_(e,n.class_error),s(e,_t),f(n.callback_error,e,a),i||N(n,a),z(l)})}function G(t,e,n){var a,i,o,r,c;t.llTempImage=document.createElement("IMG"),T(t,e,n),E(c=t)||(c[st]={backgroundImage:c.style.backgroundImage}),o=n,r=l(a=t,(i=e).data_bg),c=l(a,i.data_bg_hidpi),(r=at&&c?c:r)&&(a.style.backgroundImage='url("'.concat(r,'")'),g(a).setAttribute(ot,r),L(a,i,o)),O(t,e,n)}function D(t,e,n){var a;T(t,e,n),a=e,e=n,(t=It[(n=t).tagName])&&(t(n,a),L(n,a,e))}function V(t,e,n){var a;a=t,(-1<yt.indexOf(a.tagName)?D:G)(t,e,n)}function F(t,e,n){var a;t.setAttribute("loading","lazy"),T(t,e,n),a=e,(e=It[(n=t).tagName])&&e(n,a),s(t,vt)}function j(t){t.removeAttribute(ot),t.removeAttribute(rt),t.removeAttribute(ct)}function P(t){m(t,function(t){k(t,Et)}),k(t,Et)}function S(t){var e;(e=At[t.tagName])?e(t):E(e=t)&&(t=I(e),e.style.backgroundImage=t.backgroundImage)}function U(t,e){var n;S(t),n=e,u(e=t)||d(e)||(v(e,n.class_entered),v(e,n.class_exited),v(e,n.class_applied),v(e,n.class_loading),v(e,n.class_loaded),v(e,n.class_error)),r(t),y(t)}function $(t,e,n,a){var i;n.cancel_on_exit&&(c(t)!==ut||"IMG"===t.tagName&&(z(t),m(i=t,function(t){j(t)}),j(i),P(t),v(t,n.class_loading),p(a,-1),r(t),f(n.callback_cancel,t,e,a)))}function q(t,e,n,a){var i,o,r=(o=t,0<=pt.indexOf(c(o)));s(t,"entered"),_(t,n.class_entered),v(t,n.class_exited),i=t,o=a,n.unobserve_entered&&b(i,o),f(n.callback_enter,t,e,a),r||V(t,n,a)}function H(t){return t.use_native&&"loading"in HTMLImageElement.prototype}function B(t,i,o){t.forEach(function(t){return(a=t).isIntersecting||0<a.intersectionRatio?q(t.target,t,i,o):(e=t.target,n=t,a=i,t=o,void(u(e)||(_(e,a.class_exited),$(e,n,a,t),f(a.callback_exit,e,n,t))));var e,n,a})}function J(e,n){var t;et&&!H(e)&&(n._observer=new IntersectionObserver(function(t){B(t,e,n)},{root:(t=e).container===document?null:t.container,rootMargin:t.thresholds||t.threshold+"px"}))}function K(t){return Array.prototype.slice.call(t)}function Q(t){return t.container.querySelectorAll(t.elements_selector)}function W(t){return c(t)===_t}function X(t,e){return e=t||Q(e),K(e).filter(u)}function Y(e,t){var n;(n=Q(e),K(n).filter(W)).forEach(function(t){v(t,e.class_error),r(t)}),t.update()}function t(t,e){var n,a,t=i(t);this._settings=t,this.loadingCount=0,J(t,this),n=t,a=this,Z&&window.addEventListener("online",function(){Y(n,a)}),this.update(e)}var Z="undefined"!=typeof window,tt=Z&&!("onscroll"in window)||"undefined"!=typeof navigator&&/(gle|ing|ro)bot|crawl|spider/i.test(navigator.userAgent),et=Z&&"IntersectionObserver"in window,nt=Z&&"classList"in document.createElement("p"),at=Z&&1<window.devicePixelRatio,it={elements_selector:".lazy",container:tt||Z?document:null,threshold:300,thresholds:null,data_src:"src",data_srcset:"srcset",data_sizes:"sizes",data_bg:"bg",data_bg_hidpi:"bg-hidpi",data_bg_multi:"bg-multi",data_bg_multi_hidpi:"bg-multi-hidpi",data_poster:"poster",class_applied:"applied",class_loading:"litespeed-loading",class_loaded:"litespeed-loaded",class_error:"error",class_entered:"entered",class_exited:"exited",unobserve_completed:!0,unobserve_entered:!1,cancel_on_exit:!0,callback_enter:null,callback_exit:null,callback_applied:null,callback_loading:null,callback_loaded:null,callback_error:null,callback_finish:null,callback_cancel:null,use_native:!1},ot="src",rt="srcset",ct="sizes",lt="poster",st="llOriginalAttrs",ut="loading",dt="loaded",ft="applied",_t="error",vt="native",gt="data-",bt="ll-status",pt=[ut,dt,ft,_t],ht=[ot],mt=[ot,lt],Et=[ot,rt,ct],It={IMG:function(t,e){m(t,function(t){A(t,Et),x(t,e)}),A(t,Et),x(t,e)},IFRAME:function(t,e){A(t,ht),w(t,ot,l(t,e.data_src))},VIDEO:function(t,e){a(t,function(t){A(t,ht),w(t,ot,l(t,e.data_src))}),A(t,mt),w(t,lt,l(t,e.data_poster)),w(t,ot,l(t,e.data_src)),t.load()}},yt=["IMG","IFRAME","VIDEO"],At={IMG:P,IFRAME:function(t){k(t,ht)},VIDEO:function(t){a(t,function(t){k(t,ht)}),k(t,mt),t.load()}},kt=["IMG","IFRAME","VIDEO"];return t.prototype={update:function(t){var e,n,a,i=this._settings,o=X(t,i);{if(h(this,o.length),!tt&&et)return H(i)?(e=i,n=this,o.forEach(function(t){-1!==kt.indexOf(t.tagName)&&F(t,e,n)}),void h(n,0)):(t=this._observer,i=o,t.disconnect(),a=t,void i.forEach(function(t){a.observe(t)}));this.loadAll(o)}},destroy:function(){this._observer&&this._observer.disconnect(),Q(this._settings).forEach(function(t){y(t)}),delete this._observer,delete this._settings,delete this.loadingCount,delete this.toLoadCount},loadAll:function(t){var e=this,n=this._settings;X(t,n).forEach(function(t){b(t,e),V(t,n,e)})},restoreAll:function(){var e=this._settings;Q(e).forEach(function(t){U(t,e)})}},t.load=function(t,e){e=i(e);V(t,e)},t.resetStatus=function(t){r(t)},Z&&function(t,e){if(e)if(e.length)for(var n,a=0;n=e[a];a+=1)o(t,n);else o(t,e)}(t,window.lazyLoadOptions),t});!function(e,t){"use strict";function a(){t.body.classList.add("litespeed_lazyloaded")}function n(){console.log("[LiteSpeed] Start Lazy Load Images"),d=new LazyLoad({elements_selector:"[data-lazyloaded]",callback_finish:a}),o=function(){d.update()},e.MutationObserver&&new MutationObserver(o).observe(t.documentElement,{childList:!0,subtree:!0,attributes:!0})}var d,o;e.addEventListener?e.addEventListener("load",n,!1):e.attachEvent("onload",n)}(window,document);</script></body>
</html>
				
			
				
					html, body {
  height: 100%;
  margin: 0;
}

.grid-container {
  display: grid;
  grid-template-rows: auto 1fr auto;
  min-height: 100vh;
}

.header, .footer {
  background-color: #333;
  color: white;
  padding: 10px;
  text-align: center;
}

.content {
  padding: 20px;
}
				
			

Multiple Choice Questions

1. What does CSS stand for?

  • A) Computer Style Sheets
  • B) Cascading Style Sheets
  • C) Creative Style Sheets
  • D) Colorful Style Sheets

2. Which property is used to change the background color of an element?

  • A) bgcolor
  • B) color
  • C) background-color
  • D) bg-color

3. How do you add a comment in CSS?

  • A) // this is a comment
  • B) /* this is a comment */
  • C) <"!-- this is a comment --">
  • D) # this is a comment

4. Which property is used to change the text color of an element?

  • A) color
  • B) text-color
  • C) fgcolor
  • D) font-color

5. What is the correct syntax to link an external CSS file?

  • A) link src="styles.css"
  • B) stylesheet styles.css stylesheet
  • C) style src="styles.css"
  • D) link rel="stylesheet" href="styles.css"

6. Which property is used to change the font of an element?

  • A) font-weight
  • B) font-style
  • C) font-family
  • D) font-size

7. How do you make each word in a text start with a capital letter?

  • A) text-style: capitalize
  • B) text-transform: capitalize
  • C) transform: capitalize
  • D) text-transform: uppercase

8. Which property is used to add space between the border and the content of an element?

  • A) border-spacing
  • B) spacing
  • C) padding
  • D) margin

9. Which property is used to change the left margin of an element?

  • A) margin-left
  • B) padding-left
  • C) indent-left
  • D) spacing-left

10. How do you select an element with id "header"?

  • A) .header
  • B) *header
  • C) #header
  • D) header

11. Which CSS property controls the text size?

  • A) text-style
  • B) font-size
  • C) text-size
  • D) font-style

12. How do you make the text bold?

  • A) font-weight: bold
  • B) font-style: bold
  • C) text-style: bold
  • D) style: bold

13. Which property is used to control the order of flex items in a flex container?

  • A) item-order
  • B) flex-direction
  • C) flex-order
  • D) order

14. Which of the following is the correct way to apply a class to an HTML element?

  • A) div id="example"
  • B) div class="example"
  • C) div style="example"
  • D) div tag="example"

15. What is the default value of the position property?

  • A) absolute
  • B) fixed
  • C) relative
  • D) static

16. Which property would you use to align text to the right in an element?

  • A) text-align
  • B) align
  • C) float
  • D) vertical-align

17. How do you make a list that lists its items with squares?

  • A) list-type: square
  • B) list-style-type: square
  • C) list: square
  • D) list-style: square

18. Which property is used to change the width of an element?

  • A) height
  • B) length
  • C) width
  • D) size

19. Which property is used to specify the space between lines of text?

  • A) line-height
  • B) spacing
  • C) letter-spacing
  • D) line-spacing

20. Which of the following CSS properties is used to change the appearance of a cursor when hovering over an element?

  • A) cursor-style
  • B) hover-cursor
  • C) pointer
  • D) cursor

21. Which of the following selectors will select all (p) elements inside a (div)

  • A) div p
  • B) div + p
  • C) div > p
  • D) div ~ p

22. How do you ensure that an element stays at the top of the viewport while scrolling?

  • A) position: absolute;
  • B) position: fixed;
  • C) position: relative;
  • D) position: sticky;

23. Which CSS property is used to change the overflow behavior of an element?

  • A) overflow-mode
  • B) text-overflow
  • C) display-overflow
  • D) overflow

24. What does the z-index property control?

  • A) The stacking order of elements
  • B) The zoom level of the element
  • C) The transparency of the element
  • D) The size of the element

25. Which property is used to create space between the border and the content inside an element?

  • A) margin
  • B) border-spacing
  • C) padding
  • D) spacing

FAQ's

1. What is CSS in an interview?

Cascading Style Sheets, or CSS, are essential to modern web development since they control how web pages are presented visually and placed out. During job interviews, potential web developers, designers, or even experienced professionals frequently encounter CSS-related difficulties.

2. How to prepare for a CSS interview?
  1. Tell us a little bit about CSS3.
  2. How would one use a CSS selector?
  3. Describe CSS image scripts.
  4. Describe the specificity of CSS.
  5. In CSS, define gradients.
  6. What characteristics does flexbox have?
  7. Describe how the CSS Box Model is used.
  8. What are CSS position states?
3. What is CSS used for?

Web pages can be styled and laid out using CSS (Cascading Style Sheets). You can add animations and other visual elements that change the font, color, size, and spacing of your content, or divide it into multiple columns.

In CSS interviews, this is a typical question to see if candidates know the basics of CSS. Your response should demonstrate to the interviewer that you are familiar with styling HTML code using style sheets.

8 thoughts on “Top 30+ CSS Interview Questions and Answers”

  1. Excellent blog I liked it, detailed explanation given for each question as well as the MCQ part was interactive.

    Reply
  2. Great post! I learned something new and interesting, which I also happen to cover on my blog. It would be great to get some feedback from those who share the same interest about Airport Transfer, here is my website YK3 Thank you!

    Reply

Leave a Comment

Join Our Mailing List

Sign up for the latest news and updates.