Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

Top 20 CSS Technical Questions in Coding Interviews

Introduction

The world of web development is ever-evolving, and CSS is an essential skill for any programmer looking to thrive in this field. Whether you're a budding developer, programming enthusiast, or preparing for your next coding interview, this blog post will cover the top 20 CSS technical questions that you might come across in interviews, along with explanations and code examples to help you understand the concepts better. So, let's dive in!

1. What is CSS, and how does it work with HTML?

Interview question: Explain CSS and how it works with HTML.

Answer: CSS, or Cascading Style Sheets, is a stylesheet language used for describing the look and formatting of a document written in HTML (Hypertext Markup Language). CSS is responsible for controlling the layout, colors, fonts, and other visual aspects of a web page. It helps in separating the content of a document (HTML) from its presentation (CSS), making the web development process more accessible, organized, and maintainable.

In a typical web page, HTML elements act as a structure, while CSS styles provide the visual design. The browser reads the HTML and CSS code and combines them to render the final appearance of the web page.

Here's a simple example to demonstrate how CSS works with HTML:

<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>My Web Page</title>
  <link rel="stylesheet" href="styles.css">
</head>
<body>
  <h1>Welcome to my website!</h1>
  <p>This is an example of how CSS works with HTML.</p>
</body>
</html>
/* styles.css */
body {
  background-color: lightblue;
}

h1 {
  color: white;
  text-align: center;
}

p {
  font-family: Arial, sans-serif;
  font-size: 18px;
}

In this example, the link element in the head section of the HTML file connects the CSS file styles.css to the HTML document. The CSS file then applies the styles to the HTML elements accordingly.

2. What are CSS selectors, and what are the different types of selectors?

Interview question: Explain CSS selectors and discuss the various types of selectors.

Answer: CSS selectors are patterns used to select and target HTML elements to apply styles. There are several types of CSS selectors, including:

  1. Element (Type) selector: Targets all instances of a specific HTML element.

Example: css h1 { color: red; }   This selector will target all <h1> elements and apply the specified color.

  1. Class selector: Targets elements with a specific class attribute.

Example: ```html

This is a highlighted paragraph.

```

css .highlight { background-color: yellow; }   This selector will target any element with the highlight class and apply the specified background color.

  1. ID selector: Targets a single element with a specific id attribute.

Example: ```html

This is the main content area.

```

css #main-content { width: 80%; margin: auto; }   This selector will target the element with the id "main-content" and apply the specified width and margin.

  1. Attribute selector: Targets elements with a specific attribute or attribute value.

Example: html <input type="text" placeholder="Enter text here">

css input[type="text"] { background-color: lightgray; }   This selector will target all <input> elements with the type attribute value "text" and apply the specified background color.

  1. Pseudo-class selector: Targets elements based on their state or position in the document.

Example: html <a href="https://www.example.com">Visit our website</a>

css a:hover { color: red; }   This selector will target <a> elements when the user hovers over them and apply the specified color.

  1. Pseudo-element selector: Targets a specific part of an element.

Example: ```html

This is a paragraph with a drop cap.

```

css p::first-letter { font-size: 2em; font-weight: bold; }   This selector will target the first letter of the <p> element and apply the specified font size and weight.

  1. Combinators: Combine multiple selectors to target specific elements based on their relationships in the HTML document.

Example: ```html

This is a paragraph within a div.

This is a paragraph outside the div.

```

css div > p { color: blue; }   This selector will target only the <p> elements that are direct children of a <div> element and apply the specified color.

3. What is the box model in CSS?

Interview question: Explain the CSS box model.

Answer: The CSS box model is a fundamental concept in CSS that describes the rectangular boxes generated for elements in the document. Every HTML element can be considered as a rectangular box that consists of the following components:

  1. Content: The actual content of the element, such as text, images, or other media.
  2. Padding: The space between the content and the border, surrounding the content.
  3. Border: The line that goes around the padding and content.
  4. Margin: The space between the border and other elements outside the box.

Here's a visual representation of the box model:

+---------------------+
|                     |
|     Margin          |
|  +-------------+    |
|  |             |    |
|  |   Border    |    |
|  |  +-------+  |    |
|  |  |       |  |    |
|  |  | Padding|  |    |
|  |  |  +---+ |  |    |
|  |  |  | C | |  |    |
|  |  |  +---+ |  |    |
|  |  |       |  |    |
|  |  +-------+  |    |
|  |             |    |
|  +-------------+    |
|                     |
+---------------------+

In CSS, you can control the box model properties using the following properties:

  • width and height: Set the dimensions of the content area.
  • padding: Set the size of the padding area.
  • border: Set the size and style of the border.
  • margin: Set the size of the margin area.

Example:

<div class="box">This is an example of the CSS box model.</div>
.box {
  width: 200px;
  height: 100px;
  padding: 10px;
  border: 2px solid black;
  margin: 20px;
}

In this example, the .box class has a content area of 200x100 pixels, a padding of 10 pixels, a border of 2 pixels, and a margin of 20 pixels.

4. What is the difference between block-level and inline elements in CSS?

Interview question: Explain the difference between block-level and inline elements in CSS.

Answer: In CSS, elements are displayed in one of two ways: block-level or inline. The primary difference between them lies in how they are rendered on the page and how they interact with other elements around them.

Block-level elements: These elements create a new block or line on the page and occupy the entire width of their parent container. Examples of block-level elements include <div>, <h1> to <h6>, <p>, and <form>. Block-level elements have the following default behavior:

Start on a new line.

  1. Occupy the full width of their parent container.
  2. Accept width and height properties.

Allow padding, margin, and border properties.

Inline elements: These elements do not create a new block or line on the page and occupy only the space required for their content. Examples of inline elements include <span>, <a>, <img>, and <strong>. Inline elements have the following default behavior:

Do not start on a new line.

  1. Occupy only the space required for their content.
  2. Do not accept width and height properties.
  3. Allow padding, margin, and border properties, but may not affect surrounding elements.

You can change the default display behavior of an element using the display property in CSS. For example, you can make an inline element behave like a block-level element or vice versa.

Example:

<span class="block">This is a block-level span.</span>
<div class="inline">This is an inline div.</div>
.block {
  display: block;
  background-color: lightblue;
}

.inline {
  display: inline;
  background-color: lightgreen;
}

In this example, the <span> element with the class "block" will behave like a block-level element, while the <div> element with the class "inline" will behave like an inline element.

5. How do you apply multiple classes to an HTML element?

Interview question: Explain how to apply multiple classes to an HTML element.

Answer: To apply multiple classes to an HTML element, you can simply list the class names in the class attribute, separated by spaces.

Example:

<p class="large-text red">This paragraph has two classes applied to it.</p>
.large-text {
  font-size: 24px;
}

.red {
  color: red;
}

In this example, the <p> element has both the "large-text" and "red" classes applied to it. As a result, the text will be displayed in a larger font size and red color.

6. What is specificity in CSS, and how is it calculated?

Interview question: Explain the concept of specificity in CSS and how it is calculated.

Answer: Specificity is a mechanism in CSS that determines which style rules are applied to an element when multiple rules target the same element. In other words, specificity helps the browser resolve conflicts between competing CSS rules and decide which styles should be applied to an element.

Specificity is calculated based on the components of a CSS selector. Each selector type is assigned a specificity value, which is then combined to create a final specificity score. The styles from the selector with the highest specificity score are applied to the element.

The specificity values for different selector types are as follows:

  • Inline styles: 1,0,0,0
  • ID selectors: 0,1,0,0
  • Class selectors, attribute selectors, and pseudo-classes: 0,0,1,0
  • Element (Type) selectors and pseudo-elements: 0,0,0,1
  • Universal selector, combinators, and negation pseudo-class :not(): 0,0,0,0

Here's an example to demonstrate how specificity is calculated:

<div id="main" class="container">
  <p class="highlight">This is a paragraph with multiple styles applied.</p>
</div>
/* Specificity: 0,0,0,1 */
p {
  color: blue;
}

/* Specificity: 0,0,1,0 */
.highlight {
  color: red;
}

/* Specificity: 0,1,0,0 */
#main p {
  color: green;
}

In this example, the <p> element has three competing style rules:

  1. The element selector p has a specificity of 0,0,0,1.
  2. The class selector .highlight has a specificity of 0,0,1,0.
  3. The ID selector #main p has a specificity of 0,1,0,0.

The style with the highest specificity (0,1,0,0) will be applied, making the text color green.

7. What are the different types of CSS positioning, and how do they work?

Interview question: Explain the different types of CSS positioning and how they work.

Answer: Positioning in CSS is used to control the placement of elements on the web page. There are four main types of positioning:

  1. Static: This is the default positioning method for HTML elements. Elements with static positioning are placed in the normal document flow, according to their order in the HTML markup.

Example: ```html

This is a statically positioned element.

```

css .static { position: static; }

  1. Relative: Elements with relative positioning are positioned relative to their normal position in the document flow. You can use the top, right, bottom, and left properties to specify the offset from the normal position.

Example: ```html

This is a relatively positioned element.

```

css .relative { position: relative; top: 20px; left: 50px; }

In this example, the element will be moved 20 pixels down and 50 pixels to the right from its normal position.

  1. Absolute: Elements with absolute positioningare positioned relative to their nearest positioned ancestor, or the initial containing block if no positioned ancestor exists. The top, right, bottom, and left properties are used to specify the position of the element.

Example: ```html

This is an absolutely positioned element.

```

css .absolute { position: absolute; top: 20px; right: 30px; }

In this example, the element will be positioned 20 pixels from the top and 30 pixels from the right edge of its nearest positioned ancestor.

  1. Fixed: Elements with fixed positioning are positioned relative to the browser window, and they do not move when the page is scrolled. The top, right, bottom, and left properties are used to specify the position of the element.

Example: ```html

This is a fixed positioned element.

```

css .fixed { position: fixed; bottom: 10px; right: 10px; }

In this example, the element will be positioned 10 pixels from the bottom and 10 pixels from the right edge of the browser window.

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

Interview question: Explain the difference between display: none; and visibility: hidden; in CSS.

Answer: Both display: none; and visibility: hidden; are used to hide elements on a web page, but they have different effects on the document layout:

  • display: none; completely removes the element from the document flow. It does not take up any space on the page, and other elements will fill the space that the hidden element would have occupied.

Example: ```html

This element is hidden using display: none;

```

css .hidden1 { display: none; }

  • visibility: hidden; hides the element but maintains its position and size in the layout. The element still takes up space on the page, but its content is invisible.

Example: ```html

This element is hidden using visibility: hidden;

```

css .hidden2 { visibility: hidden; }

9. What is the !important rule in CSS, and when should you use it?

Interview question: Explain the !important rule in CSS and its use cases.

Answer: The !important rule is used in CSS to give higher precedence to a specific style declaration, overriding any other declarations that would normally apply due to specificity, inheritance, or the ordering of rules.

It should be used sparingly and only in situations where it is absolutely necessary, as it can make the CSS code harder to maintain and debug. Some use cases for !important include:

  • Overriding third-party styles when modifying or extending a pre-built component or library.
  • Temporarily applying a style during development or debugging.

Example:

<div class="highlight">This is a paragraph with multiple styles applied.</div>
.highlight {
  color: red;
}

.highlight {
  color: blue !important;
}

In this example, the paragraph text color will be blue, as the !important rule gives the second .highlight declaration higher precedence than the first one.

10. What are CSS media queries, and how are they used for responsive design?

Interview question: Explain CSS media queries and their role in responsive web design.

Answer: CSS media queries are a technique used to apply different styles based on the characteristics of the user's device, such as screen width, screen height, or device type. They are a key component of responsive web design, allowing developers to create layouts that adapt to different screen sizes and orientations.

A media query consists of a media type, such as screen or print, and one or more expressions that evaluate to true or false. If the media type and expressions match the user's device, the styles within the media query block will be applied.

Example:

/* Default styles for all devices */
body {
  font-size: 16px;
}

/* Styles for screens with a width of 768 pixels or more */
@media screen and (min-width: 768px) {
  body {
    font-size: 18px;
  }
}

/* Styles for screens with a width of 1024 pixels or more */
@media screen and (min-width: 1024px) {
  body {
    font-size: 20px;
  }
}

In this example, the font size of the body element will change based on the screen width, creating a responsive typography experience.

11. What is the difference between margin and padding in CSS?

Interview question: Explain the difference between margin and padding in CSS.

Answer: Both margin and padding are properties used for spacing in CSS, but they serve different purposes:

  • margin: Refers to the space outside an element's border. It is used to create space around elements, separating them from other elements on the page. Margins are transparent and do not accept background colors.
  • padding: Refers to the space between an element's content and its border. It is used to create space within an element, making the content easier to read or interact with. Padding inherits the element's background color.

Example:

<div class="container">
  <div class="element">This is an element with margin and padding.</div>
</div>
.container {
  background-color: lightgray;
}

.element {
  background-color: white;
  margin: 20px;
  padding: 20px;
}

In this example, the .element has a 20-pixel space outside its border (margin) and a 20-pixel space between its content and border (padding).

12. What are CSS pseudo-classes and pseudo-elements?

Interview question: Explain the concepts of CSS pseudo-classes and pseudo-elements and provide examples.

Answer: Pseudo-classes and pseudo-elements are special selectors in CSS that allow developers to style specific parts of an element or elements under particular conditions.

  • Pseudo-classes: These are used to target elements based on their state, position, or other properties. They are denoted by a colon followed by the pseudo-class name (e.g., :hover, :first-child). Some common pseudo-classes include:
  • :hover: Targets an element when the user hovers over it.
  • :first-child: Targets the first element among a group of sibling elements.
  • :last-child: Targets the last element among a group of sibling elements.
  • :nth-child(): Targets an element based on its position among its siblings.

Example: ```css / Change the color of a link when it is hovered over / a:hover { color: red; }

/ Style the first and last list item in a list / li:first-child { font-weight: bold; } li:last-child { font-style: italic; } ```

  • Pseudo-elements: These are used to target and style specific parts of an element, such as the first letter or line of text, or to insert content before or after an element. Pseudo-elements are denoted by two colons followed by the pseudo-element name (e.g., ::before, ::after). Some common pseudo-elements include:
  • ::before: Inserts content before an element.
  • ::after: Inserts content after an element.
  • ::first-letter: Targets the first letter of a block-level element.
  • ::first-line: Targets the first line of a block-level element.

Example: ```css / Add a quote icon before a blockquote element / blockquote::before { content: "“"; font-size: 2em; margin-right: 10px; }

/ Style the first letter of a paragraph / p::first-letter { font-size: 2em; font-weight: bold; } ```

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

Interview question: Explain the difference between em and rem units in CSS and when to use them.

Answer: Both em and rem are relative units of measurement in CSS, used for sizing elements in relation to a base font size. They are useful for creating scalable and accessible designs that respond to user preferences and browser settings.

  • em: Refers to the font size of the element's parent or the element itself when applied to properties like font-size. For instance, if an element has a parent with a font size of 16 pixels, 1em for the element is equal to 16 pixels.
  • rem: Refers to the font size of the root element (usually the <html> element). If the root element has a font size of 16 pixels, 1rem is equal to 16 pixels, regardless of the font size of any parent elements.

Example:

<html>
  <body>
    <div class="parent">
      <p class="child">This is a paragraph with relative font sizes.</p>
    </div>
  </body>
</html>
html {
  font-size: 16px;
}

.parent {
  font-size: 20px;
}

.child {
  font-size: 1em; /* 20 pixels, based on the parent font size */
  margin-bottom: 1rem; /* 16 pixels, based on the root font size */
}

In this example, the paragraph's font size is set using em, making it 20 pixels, based on the parent's font size. The margin below the paragraph is set using rem, making it 16 pixels, based on the root font size.

14. How do you create a responsive grid layout in CSS?

Interview question: Explain how to create a responsive grid layout using CSS.

Answer: A responsive grid layout can be created using CSS Grid, Flexbox, or other techniques like floats and media queries. In this answer, we will use CSS Grid, a powerful layout system designed for creating complex, responsive layouts with ease.

Example:

<div class="grid-container">
  <div class="grid-item">Item 1</div>
  <div class="grid-item">Item 2</div>
  <div class="grid-item">Item 3</div>
  <div class="grid-item">Item 4</div>
  <div class="grid-item">Item 5</div>
  <div class="grid-item">Item 6</div>
</div>
.grid-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  grid-gap: 10px;
}

.grid-item {
  background-color: lightgray;
  padding: 20px;
  text-align: center;
}

In this example, we create a responsive grid layout with a flexible number of columns. The grid-template-columns property uses the repeat() function with auto-fit and minmax() to create columns that are at least 200 pixels wide and distribute available space evenly. The grid-gap property sets the space between grid cells.

15. What is the CSS cascade, and how does it affect the order in which styles are applied?

Interview question: Explain the concept of the CSS cascade and its role in determining the order in which styles are applied.

Answer: The CSS cascade is a set of rules that determine the order in which styles are applied to elements on a web page. It ensures that the most specific and relevant styles take precedence over more general ones. The cascade is based on the following factors:

  1. Importance: Styles marked with !important have higher precedence than those without.
  2. Specificity: Styles with more specific selectors (e.g., targeting an element's ID or class) have higher precedence than those with less specific selectors (e.g., targeting an element's tag).
  3. Source order: If two styles have the same importance and specificity, the one that appears later in the CSS will take precedence.

Example:

<div id="example" class="box">This is a styled element.</div>
/* Lower specificity: applied first */
div {
  color: red;
}

/* Higher specificity: applied second */
.box {
  color: blue;
}

/* Highest specificity: applied third */
#example {
  color: green;
}

/* !important: applied last */
.box {
  color: purple !important;
}

In this example, the text color of the div will be purple, as the !important rule takes precedence over all other styles. Without the !important rule, the text color would be green, based on the highest specificity.

16. What are CSS custom properties (variables), and how are they used?

Interview question: Explain CSS custom properties (variables) and their use cases.

Answer: CSS custom properties, also known as CSS variables, are a way to store reusable values in a stylesheet and make it easier to maintain and update styles. They can be used for colors, font sizes, spacing, or any other values that are used throughout a design.

Custom properties are declared using the -- syntax and can be accessed using the var() function.

Example:

:root {
  --primary-color: #007bff;
  --secondary-color: #6c757d;
  --font-size: 16px;
  --spacing: 10px;
}

body {
  font-size: var(--font-size);
}

button.primary {
  background-color: var(--primary-color);
  color: white;
  margin: var(--spacing);
}

button.secondary {
  background-color: var(--secondary-color);
  color: white;
  margin: var(--spacing);
}

In this example, we declare a set of custom properties for colors, font size, and spacing on the :root element. These properties can then be used throughout the stylesheet with the var() function, making it easier to update the design in the future.

17. How do you create a CSS animation?

Interview question: Explain how to create a CSS animation and provide an example.

Answer: CSS animations can be created using the @keyframes rule and the animation property. The @keyframes rule is used to define the animation's keyframes, which represent different points in the animation sequence and their corresponding styles. The animation property is then applied to the elements to be animated, specifying the name of the @keyframes rule, the duration, and other settings.

Example:

<div class="box">This is an animated element.</div>
@keyframes fadeInOut {
  0%, 100% {
    opacity: 0;
  }
  50% {
    opacity: 1;
  }
}

.box {
  animation: fadeInOut 3s infinite;
}

In this example, we create a simple fadeInOut animation using the @keyframes rule. The animation starts with an opacity of 0, increases to 1 at the halfway point, and then decreases back to 0 at the end. The animation is applied to the .box element with a duration of 3 seconds and is set to loop infinitely.

18. What is the difference between CSS transitions and animations?

Interview question: Explain the difference between CSS transitions and animations.

Answer: Both CSS transitions and animations are used to create smooth, time-based changes to an element's style. However, they serve different purposes and have different levels of complexity:

  • Transitions: CSS transitions are a simpler way to create animations for property changes that occur as a result of user actions, such as hovering over an element or changing the state of a form control. Transitions automatically generate intermediate frames between the start and end values of the properties being animated, creating a smooth effect. Transitions are defined using the transition property.

Example: ```css button { background-color: blue; transition: background-color 0.5s; }

button:hover { background-color: red; } ```

In this example, the button's background color changes smoothly from blue to red when the user hovers over it, thanks to the transition property.

  • Animations: CSS animations are a more powerful and flexible way to create complex, time-based animations with multiple keyframes and properties. They are defined using the @keyframes rule and the animation property, as described in the previous answer.

In summary, transitions are best suited for simple animations triggered by user actions, while animations are better for more complex, multi-step animations that may not rely on user interaction.

19. How do you create a CSS gradient?

Interview question: Explain how to create a CSS gradient, and provide an example.

Answer: CSS gradients are a way to display a smooth transition between two or more colors on an element's background. There are two types of gradients: linear and radial.

  • Linear Gradient: A linear gradient transitions colors along a straight line. It can be created using the linear-gradient() function. The function accepts two or more color stops and an optional angle or direction.

Example: css .box { background-image: linear-gradient(to right, red, yellow); }

In this example, we create a horizontal linear gradient that transitions from red to yellow from left to right.

  • Radial Gradient: A radial gradient transitions colors in a circular pattern, with a center point and an ending shape (circle or ellipse). It can be created using the radial-gradient() function. The function accepts two or more color stops and an optional shape and size.

Example: css .box { background-image: radial-gradient(circle, red, yellow); }

In this example, we create a circular radial gradient that transitions from red in the center to yellow at the edges.

20. What is the purpose of CSS preprocessors, and what are some examples?

Interview question: Explain the purpose and benefits of CSS preprocessors, and provide some examples.

Answer: CSS preprocessors are scripting languages that extend the capabilities of CSS and are compiled into standard CSS code. They introduce additional features like variables, mixins, functions, and nested rules, which make it easier to write and maintain complex stylesheets.

Some of the main benefits of using a CSS preprocessor include:

  • Modularity and organization: Preprocessors allow for better organization and modularity by using partials, imports, and nested rules.
  • Reusability: Variables, mixins, and functions make it easy to reuse code and maintain consistency throughout the project.
  • Maintainability: Preprocessors make it easier to manage large codebases by providing additional features and tools for better organization and readability.

Some popular CSS preprocessors include:

Sass (Syntactically Awesome Style Sheets): Sass is one of the most popular CSS preprocessors. It uses a syntax similar to CSS but adds powerful features like variables, nested rules, mixins, and functions. Sass files have a .scss or .sass extension.

Less (Leaner Style Sheets): Less is another popular CSS preprocessor, similar to Sass. It extends CSS with features like variables, mixins, and nested rules. Less files have a .less extension.

Stylus: Stylus is a flexible and expressive CSS preprocessor, inspired by Sass and Less. It allows for a more concise syntax and omits brackets, colons, and semicolons. Stylus files have a .styl extension.

Conclusion

In this blog post, we have covered 20 technical CSS questions that are commonly asked during coding interviews. These questions range from basic concepts like the box model and specificity to more advanced topics like animations and preprocessors. By understanding these concepts and practicing with code examples, you'll be better prepared for your next web development interview and have a solid foundation in CSS.