Top 50 CSS Interview Questions (With Code Examples!)

Jacinto Wong
Jacinto Wong
hero image

Are you preparing for a job interview as a front-end web developer, and want to brush up on your CSS knowledge?

Well, good news!

Welcome to Part 2 in my series of the most common technical interview questions for front-end web developers:

Why do we need to prepare for each of these?

Well, as you well know, CSS, HTML and JavaScript are all used in combination with each other, so there’s a very high chance that you’ll need to answer questions on each of these 3 topics.

With that in mind, I’m going to break down the common CSS and HTML questions below, along with answers to those questions, and code snippet examples.

So grab a coffee, read through, recap what you know, find out some new things, and get ready to smash that job interview!

Sidenote:

If you struggle to understand any of the questions in this guide, or want to improve your current skills, then check out my complete CSS digital bootcamp.

learn CSS

You’ll learn everything from CSS basics to advanced CSS techniques by completing 100+ exercises and 10 projects.

This course will help you learn how to use CSS to create beautiful, responsive websites that wow users and employers. Become a CSS Pro and never create an ugly website again.

With that out of the way, let’s get into the interview questions…

Beginner CSS interview questions

Alright, let’s start nice and easy so we can prove we know what CSS is and the basics of how it works.

Why do we use CSS?

The simple answer is that it's vital for modern web design! However, there’s 4 main points that I think should be covered.

CSS allows for separation of content and design

One of the main benefits of using CSS is that it separates content from design. HTML takes care of the structure and content, while CSS handles the layout and styling.

This separation makes content more accessible and gives you greater flexibility and control over how your website looks

Increased efficiency and control

CSS lets you manage the layout of multiple web pages all at once.

For example

If you want to change the color scheme of your entire site, you just need to update one CSS file instead of manually editing each HTML file. This makes your work much more efficient.

Enhanced user experience

With CSS, you can create a consistent and attractive user interface that helps users feel familiar with your site. You can control the colors, fonts, and spacing, add backgrounds, and even include animations to enhance the visual appeal.

For example

Here is a section of CSS code.

body {
    font-family: Arial, sans-serif;
    background-color: dodgerblue;
    color: #333;
}

And here is the HTML, with no CSS:

hello world

By default, the font family is Times New Roman with a black color and white background.

Here is the same content with our CSS added:

hello world with css added

This CSS snippet sets the font for the body to Arial, the background color to dodger blue (which is one of many named colors), and the text color to dark gray.

One of the first things I change in a project is the font-family as it makes a huge difference, and the reason I’m choosing Arial here is that it is included by default on almost every device.

Device adaptability

With the variety of devices available today, all having different screen sizes and resolutions, CSS is essential. It enables you to create responsive designs that adapt to various screen sizes, ensuring your website looks great on any device.

Google recently announced that they will soon only index websites if they are mobile optimized, so this is more important than ever.

What are the advantages of using CSS?

Design consistency

CSS ensures design consistency across the website by applying the same styles and formats from a single file to multiple pages. Providing a consistent user experience is key to user engagement and satisfaction.

For example

/* CSS code to apply consistent style */
body {
    font-family: Arial, sans-serif;
    background-color: dodgerblue;
    color: #333;
}
body styling

We can see here that the <h1> header element and <p> paragraph element are both affected by the body styling.

By adding this, we could then keep the styling for all future <h1> header elements.

Efficient changes

This ability to control the layout of multiple web pages with a single style sheet leads to considerable efficiency.

Change one line of code, and see it reflected across your entire site.

Responsive designs

CSS enables the creation of responsive designs that adapt to different devices and screen sizes, enhancing user experience. Using media queries, you can apply different styles for different devices.

This is something I believe has become even more important now that most people are accessing websites on their smartphones rather than a laptop or desktop device.

For example

/* CSS code for a media query */
@media screen and (max-width: 600px) {
    h1{
   	   font-size: 28px;
    }
}

We can see the difference in header size in these two cases.

Here's the desktop version:

desktop

And here's the mobile version:

mobile version

SEO benefits

CSS can enhance a website's search engine optimization by improving load times and making it easier for search engines to crawl the site.

Presentation flexibility

CSS allows you to present the same HTML document in different viewing styles, like on-screen, print, or even voice rendering, enhancing accessibility.

I’ve personally found this extremely useful, as I’m able to utilize the browser’s native print functionality to print a table of data, but without the navigation bar, search inputs, etc.

How to include CSS in a webpage?

There are three primary methods to incorporate CSS into a webpage, and they are as follows:

Inline CSS

Inline CSS involves adding CSS rules directly within the HTML elements using style attribute.

For example

<p style="color:blue; font-size:14px;">This paragraph will be blue and the font size will be 14px.</p>
inline css

Internal CSS

Internal CSS involves adding CSS rules within the style tags, placed inside the head element of your HTML document.

For example

<!DOCTYPE html>
<html>
<head>
    <style>
   	 p {
   		   color: red;
   		   font-size: 24px;
   	 }
    </style>
</head>
<body>
    <p>This paragraph will be red and the font size will be 24px.</p>
</body>
</html>

Same text as before, but we have changed the color property.

internal css

External CSS

External CSS involves linking to an external .css file within your HTML document, and the .css file contains your CSS rules.

This method is best for larger projects with many HTML documents, and is the method that you’ll likely use most often.

For example

In your HTML file:

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
    <p>This paragraph will use the styles defined in the 'styles.css' file.</p>
</body>
</html>

And in your CSS file (styles.css):

p {
    color: green;
    font-size: 24px;
}
external css

In summary, the method you choose to include CSS in your webpage depends on the scale of your project or specific needs of your HTML elements. You can use inline styles to overwrite styles from a stylesheet as they are processed last.

How can we add comments in CSS?

Comments in CSS are written inside /* and */ symbols.

They are used in CSS to explain the code, and they can be very helpful for both the author and other developers who may encounter the code. They are ignored by the browser and do not affect the final output.

I will usually always add comments in HTML to separate different elements and sections, then I will group the CSS related to those with similar comments, and lastly with JS I will usually go into more detail on what a specific function does.

For example

/* This is a single-line comment */

/*
This is a
multi-line comment
*/

In the above examples, the text within the /* and */ will be ignored by the browser. This can be used to add useful context or disable certain lines of CSS code.

What does the ‘a' in rgba mean?

In CSS, rgba stands for red green blue alpha.

While red, green, and blue are primary colors and represented by numbers between 0 and 255 (0 is the absence of the color and 255 is the maximum amount of the color), the 'a' in rgba stands for alpha, and represents the color's opacity level.

The alpha value is a number between 0.0 (completely transparent) and 1.0 (completely opaque).

For example

    background: rgba(255, 0, 0, 0.3);
opaque red

In this example, the color is pure red, with no green or blue (255, 0, 0), and the opacity is 0.3 (0.3).

While in the example below, we have the opacity set to 1, which is the default and we can see that it’s bright red.

full red

What are CSS HSL Colors?

HSL stands for Hue, Saturation, and Lightness. It is a color scheme that is supported in CSS3.

  • Hue: Hue is a degree on the color wheel from 0 to 360. 0 is red, 120 is green, and 240 is blue
  • Saturation: Saturation is a percentage value; 100% is full color and 0% is a shade of gray
  • Lightness: Lightness is also a percentage; 0% is black, 100% is white, and 50% is normal lightness

For example

body {
	background-color: hsl(120, 100%, 50%);
}
css hsl colours

In this example, the background color of the body is set to a bright and light green. That's because the hue is set to 120 (which is green), the saturation is set to 100% (full color), and the lightness is set to 50% (normal lightness).

In summary, HSL color values provide a more intuitive way to select colors.

The biggest benefit I notice when using this method, is that it makes it easier to make complementary colors by changing the saturation and lightness while having the hue remain the same.

Also, with the addition of the alpha channel, HSLA can also support transparency, just as we saw in our previous RGBA example.

What property is used for changing the font?

The font-family property is used in CSS to specify the font face of a text. It's a priority list of font families, listed in order of preference.

For example

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

In this example, the browser will try to display the text in Arial. If it can't, it will fall back to any available sans-serif font.

This allows for fine control and flexibility in specifying the typography of a webpage, while ensuring there will always be a font displayed if the first choice is not available.

Besides using the locally available fonts, CSS also allows the use of web fonts which are downloaded from a server. The easiest way to do this is by using Google Fonts, which can be done through an @import statement at the top of your CSS file.

For example

@import url('https://fonts.googleapis.com/css2?family=Major+Mono+Display&family=Roboto&display=swap');

p {
font-family: "Major Mono Display", Arial, sans-serif;
}
google fonts

In the above code, the browser will attempt to use 'Major Mono Display' if it's available. (This is an imported and frankly horrible font).

If the font is not available, it falls back to Arial, and then to sans-serif.

What are the different CSS border properties?

CSS provides a variety of border properties to style the borders of a box, usually represented by a <div> element.

Border-width

This specifies the width of the border. The values may be thin, medium, thick, or a specific size in px, pt, cm, em, etc.

For example

div {
    border-width: 5px;
}
border widthe

Border-style

This specifies the style of the border. Some of the values can be none, hidden, dotted, dashed, solid, double, groove, ridge, inset, outset.

For example

div {
    border-style: dashed;
}
dashed border

Border-color

This specifies the color of the border. The color can be a color name, hex value, rgb value, etc.

For example

div {
    border-color: #ff0000;
}
border colour

Border-radius

Defines the radius of the border's corners.

This is something used a lot in modern web development. If you look at most Google products for example, they will round the corners of most containers to give a more modern look.

For example

div {
    border-radius: 10px;
}
border radius

Border

A shorthand property for setting the width, style, and color of an element's border.

This is usually how I would personally add a border because it’s more efficient to write as shorthand.

For example

div {
    border: 2px solid #ff0000;
}
solid border

What is the difference between margin and padding?

Margin and padding are key components of the CSS Box Model, which encloses every HTML element.

Margin

Margin refers to the space around an element.

It's the space outside the border, between the border of the element and its surrounding elements. So if you want to add space between your element and the next one, you add margin to your element.

For example

div {
    margin: 20px;
}

Padding

Padding, on the other hand, is the space between the content of the element and its border.

If you want to give your content some breathing room inside the border, you add padding. This is something you should always be adding to containers when they contain text to make it easier to read.

For example

As you can see the box on the top doesn’t have padding and isn’t as easy to read.

div {
    padding: 20px;
}
margin and padding

So, the main difference between margin and padding is what they apply space to. Margin adds space outside the element border, and padding adds space inside the border.

What does margin: 40px 100px 120px 80px signify?

This is a shorthand manner to specify the margins for all four sides of an element.

div {
    margin: 40px 100px 120px 80px;
}

So let me explain.

In CSS, the margin property can accept up to four values, and they apply to the top, right, bottom, and left margins respectively.

For example

If we look at the code example in the question:

  • First Value (40px): The first value is for the top margin. So, the top margin of the element will be set to 40px.
  • Second Value (100px): The second value is for the right margin. The right margin will be set to 100px.
  • Third Value (120px): The third value is for the bottom margin. This sets the bottom margin to 120px.
  • Fourth Value (80px): The fourth value is for the left margin. It sets the left margin to 80px.
margin adjustments

This is a good way to consolidate your margin properties.

You don’t have to use all 4 values either. You could go with 2, 3 or 4 values.

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

VH and VW are CSS units related to the viewport size.

"VH" stands for viewport height, and "VW" stands for viewport width, and these are extremely useful for creating responsive designs.

VH explained

One unit on the VH scale is equal to 1% of the viewport height. So, if you have an element with a style of height: 50vh;, that element will take up 50% of the height of the viewport.

For example

div {
    height: 50vh;
}

VW explained

Similarly, one unit on the VW scale is equal to 1% of the viewport width. So this means that an element with a style of width: 80vw; will take up 80% of the width of the viewport.

For example

div {
    width: 80vw;
}
VW explained

Why use these?

These units are incredibly powerful because they allow you to size elements and fonts to be a percentage of the size of the viewport.

I would definitely recommend using these values for responsive design.

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

In CSS, display is a powerful property that dictates how an element behaves in terms of flow and formatting context. The values block, inline, and inline-block each make an element behave in a unique way.

Block-Level elements

Block-level elements always start on a new line and take up the full width available. They extend in the block direction, to be as wide as their parent element.

Examples of block elements include <div>, <h1>-<h6>, <p>, and <form>

For example

div {
    display: block;
}

In the above example, the div will take up the full width of its parent, and any content following it will start on a new line.

Inline elements

Unlike block-level elements, inline elements do not start on a new line. They only take up as much width as necessary for the content. Examples of inline elements include <span>, <a>, and <img>.

For example

span {
    display: inline;
}

In the above example, spans will lay out horizontally, as much as it can fit on one line.

Inline-Block elements

Inline-block elements are a hybrid of the two. They can have a width and height set, which is not possible with inline elements, but they still maintain their inline-level placement.

This means they will sit on the same line as other elements, but you can manipulate their size.

For example

button {
    display: inline-block;
    width: 600px;
}

In the above example, the button will have inline placement but has a width of 600px.

Inline-Block elements

The main differences between block, inline, and inline-block center around how they handle width, height, and line breaks.

While the choice between them will depend on the specific layout and formatting needs for your web content.

How do you specify units in CSS, and what are the different ways to do it?

In CSS, units are used to specify non-zero length values, such as margins, width, font-size, and more. There are various units available, each with their unique applications.

Absolute lengths

These are the most straightforward, as they represent a physical measurement. The most commonly used is the pixel (px).

For example

div {
    width: 300px;
}

The div will render at 300 pixels wide.

absolute lengths

Relative lengths

These are relative to something else on the page, such as the size of the parent element, the size of the viewport, or the font size.

em

The size is relative to the parent element's font size.

For example

p {
font-size: 1.2em;
}

The paragraph text will be 1.2 times the size of the parent element's font. In this case, I made the font-size for the body 30px, so, it would become 36px.

rem

Similar to em, but instead of being relative to the parent's font size, it's relative to the root (or <html>) element's size.

Because by default the root font size is 16px, this is actually smaller at only 24px.

relative root length
vw (viewport width) and vh (viewport height)

These units are relative to the viewport's size.

**For example **

div {
 width: 50vw;
 height: 50vh;
}

The div will be 50% of the viewport's width and height.

viewport width and viewport height

By understanding these units and their different use cases, you can build more adaptive layouts and create a better responsive design.

Relative units like vw and vh can definitely be very useful when you want to accommodate screen sizes, with things that are okay at different sizes like images, sections of pages, etc.

However, I would suggest that there are instances, like modals and search inputs and things like that where it might be better to have a consistent size every time so that you are able to fit everything you want to fit in your layout.

It is definitely important to understand the best time to use one or the other.

What are CSS backgrounds properties?

The CSS background properties are used to add styled backgrounds to different elements.

They enable control over:

  • Color
  • Image
  • Position
  • Size
  • And other aspects of the background

They can also be combined in a shorthand property to control everything at once.

background-color

Sets the background color of an element. It takes color names, RGB, HEX, HSL, RGBA, HSLA values.

For example

body {
  background-color: #f0f0f0;
}
background color

background-image

Sets an image as the background of an element.

The value can be a URL or a data URI. By default, it is set to repeat if the image is too small, in this case, the image is 100x100 pixels.

For example

body {
 background-image: url("unsplash-nature.jpg");
}
background image

Background-repeat

This defines if/how a background image should be repeated. The values can be repeat, repeat-x, repeat-y, no-repeat.

In the following example, we have the same small image as before, but we are setting it to no-repeat so we are only seeing it once. Without specifying the position, by default it will appear in the top left.

For example

body {
 background-image: url("unsplash-nature.jpg");
 background-repeat: no-repeat;
}
background no repeat

Background-position

This specifies the position of a background image.

The first value is the horizontal position, and the second value is the vertical. This means that top, bottom, right, left, center, or a percentage or length in pixels can be specified.

For example

In this example, we are setting the position to be the top right corner.

body {
 background-image: url("unsplash-nature.jpg");
 background-position: right top;
}
background position

Background-size

This specifies the size of the background image. The first value sets the width, and the second value sets the height.

So, you could set it as 500px 500px for example. If only one value is given, the second is set to auto. Possible values are auto, length (in pixels), percentage, cover, contain.

For example

The following example uses the size cover, meaning it will fill the container without skewing the image, if the image is too small it will zoom in to fill the container.

body {
 background-image: url("unsplash-nature.jpg");
 background-size: cover;
}
background size

Background-attachment

This determines whether a background image scrolls with the rest of the page, or is fixed. Possible values are scroll, fixed, local.

For example

In this case, having the fixed background-attachment causes the image to reveal different parts as the page is scrolled, with the image itself actually not moving.

body {
   	 background-image: url("unsplash-nature.jpg");
   	 background-attachment: fixed;
}
background attachment

Background

This is a shorthand property for setting all the background properties in one go, and it can take all the values mentioned above.

For example

In the example below, we are adding a background color, with an image that doesn’t repeat and is centered.

body {
   	 background: #f0f0f0 url("unsplash-nature.jpg") no-repeat center;
}
background additions

What are Pseudo elements and Pseudo classes?

In CSS, pseudo elements and pseudo classes allow developers to style specific parts of a document tree, often dynamically based on user interaction or document state.

Pseudo classes explained

Pseudo classes are used to define certain states of an element, and are written as a keyword preceded by a colon, for example :hover, :active, or :visited.

For example

a:hover {
	color: red;
}

The above code snippet changes the text color from blue to red when the user hovers over a hyperlink.

Pseudo classes explained

The hover pseudo class is the one I use most often to show the user that something can be interacted with like a button or link.

Pseudo elements explained

On the other hand, pseudo elements are used to style a specific part of an element, such as the first letter or line, or to add something to the element.

They are written as a keyword preceded by two colons, for example ::before or ::after.

For example

p::first-line {
	font-weight: bold;
	color: blue;
}
Pseudo elements explained

In this example, the ::first-line pseudo element is used to make the first line of every paragraph bold and blue.

Both pseudo classes and pseudo elements allow developers to finely control stylings based on dynamic states or specific portions of an element.

What do the following CSS selectors mean?

CSS selectors are patterns used to select elements you want to style.

Element selector

An element selector selects elements based on the element name.

For example

  <p>This paragraph is styled using the element selector.</p>
p {
  color: red;
  padding: 10px;
  border: 1px solid #ccc;
  background-color: #fff;
  margin-bottom: 10px;
}

In this example, all paragraph text will be red.

element selector

Class selector

A class selector selects elements with a specific class attribute. It's denoted by a period . followed by the class name.

For example

    <p class="myClass">This paragraph is styled using the class selector.</p>
.myClass {
  font-size: 1.5em;
  color: green;
}

In this example, all elements with class="myClass" will have their font size set to 1.5em and the color is green.

class selector

It is also still inheriting the properties from the paragraph selector as well, though the color is overridden because the class selector has more specificity.

ID selector

An ID selector selects an element with a specific id attribute. It's denoted by a hash # followed by the ID value.

For example

    <p id="myID">This paragraph is styled using the ID selector.</p>
#myID {
  background-color: yellow;
  color: black;
}
id selector

In this example, the element with id="myID" will have a yellow background with black text, also inheriting some of the original properties from the paragraph selector.

Pseudo-class selector

A pseudo-class selector selects elements in a certain state, like :hover or :active.

For example

In this example, the color of links becomes purple when hovered over and the underline is removed that is there by default on an anchor element.

a:hover {
  color: purple;
  text-decoration: none;
}
Pseudo-class selector

This is just the surface of CSS selectors, with many more complex selectors like child, adjacent sibling, attribute selectors, and more.

How can you align content inside the paragraph tag at the exact center inside the div?

Centering content vertically and horizontally in CSS can be achieved in various ways. Let's consider one of the most modern and efficient ways - using Flexbox.

To center content inside a <p> tag at the exact center of a <div>, you can make the div a flex container and then use justify-content and align-items properties, as shown below:

div {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}
centered content

Here, the display: flex; rule makes the div a Flexbox container, while justify-content: center; and align-items: center; center the child elements horizontally and vertically, respectively.

Remember that for align-items to work, the div needs to have a set height, hence height: 100%;.

What are the different box-sizing properties?

In CSS, the box-sizing property determines how the dimensions (width and height) of elements are calculated.

There are two main values for box-sizing: content-box and border-box.

content-box

This is the default CSS box model. If set to content-box, the width and height properties include the content of the element, but do not include padding, borders, or margins.

So, if you add padding or borders, the size of the box will grow which might result in layout issues.

For example

div {
  box-sizing: content-box;
  width: 300px;
  padding: 10px;
  border: 5px solid black;
}
content box

In the above example, the total computed width of the div will be 330px (300px width + 2 * 10px padding + 2 * 5px border).

border-box

When set to border-box, the width and height properties include the content, padding, and border, but do not include the margin.

Hence, adding padding or border doesn't affect the final computed box width.

For example

div {
  box-sizing: border-box;
  width: 300px;
  padding: 10px;
  border: 5px solid black;
}
border box

In this case, the total computed width of the div will still be 300px. The padding and border are included in the box's size.

This is something important to consider when you want to add padding inside a container, but you have a set size that you want the whole container to take up.

How is opacity specified in CSS3?

In CSS3, you can control the opacity or transparency level of an element using the opacity property or the RGBA and HSLA color schemes.

Opacity property

The opacity property can take a value from 0.0 - 1.0. A lower value makes the element more transparent.

For example

div {
    opacity: 0.5;
}
Opacity property in css3

In this example, the div element will have 50% opacity, meaning it will appear semi-transparent. You can see the comparison with a div with 100% opacity.

RGBA

Transparency can also be achieved using RGBA color values, like I mentioned before.

For example

div {
    background-color: rgba(255, 0, 0, 0.3);
}
rgba opacity in css3

In this example, the div background color is set to red (255, 0, 0), with an opacity level of 0.3, so the background will appear as a transparent red.

While we can see the border has a higher opacity value and appears darker.

HSLA

Similar to RGBA, HSLA color scheme also allows for specifying opacity.

For example

div {
    background-color: hsla(120, 100%, 50%, 0.3);
}
hsla opacity in css3

In this example, the div background color is set to a shade of green (120, 100%, 50%) and with an opacity level of 0.3.

This example also has a higher opacity value on the border.

TL;DR

CSS3 gives developers control over the transparency and overall aesthetic of their web elements.

I usually find this very useful for hover effects or if I want to add an overlay over my page to de-focus on the main content of the page behind a modal, or even on a video background having a low opacity black div to allow for text on top of the video background to be easily readable.

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

In CSS, we have several ways to hide an element, each with its own use cases and implications. Here are three of the most common methods:

Display

The display property can be set to none to hide an element completely. This removes the element from the normal document flow, and it takes up no space.

For example

element {
  display: none;
}

Visibility

The visibility property can be set to hidden to make an element invisible.

Unlike display: none, the element is still in the document flow and occupies its original space, it's just not visible.

For example

element {
  visibility: hidden;
}

Opacity

The opacity property can be set to 0 to make an element completely transparent but not hidden.

Like visibility: hidden, the element remains in the document flow. However, it's possible to interact with it, such as clicking a link inside it.

For example

element {
  opacity: 0;
}

Choosing a method depends on what you need:

  • If you want to hide an element completely and free up its space, use display: none
  • If you want to make it invisible without changing the layout, use visibility: hidden
  • If you want to create a fade effect, opacity: 0 can be used

Remember though, hidden elements can still be accessed by screen readers, so don't use these properties to hide sensitive information.

What does the :root pseudo-class refer to?

In CSS, the :root pseudo-class represents the root of the document. (Whereas in HTML, :root typically refers to the <html> element).

Accessing the :root pseudo-class can be particularly useful when dealing with CSS variables (also known as "custom properties").

You can declare a CSS variable in the root scope and then use it anywhere in your document.

Accessing the :root pseudo-class can be particularly useful when dealing with CSS variables (also known as "custom properties").

You can declare a CSS variable in the root scope and then use it anywhere in your document.

For example

:root {
  --main-color: #06c;
  --accent-color: #006;
}

#div1 {
  background-color: var(--main-color);
  color: var(--accent-color);
}
root pseudo class

In this example, two CSS variables are defined: --main-color and --accent-color.

But because these are defined in the :root, they can be used anywhere in the document. (The #div1 styles apply these variables).

The benefits of using CSS variables is most apparent when creating :root level colors, alongside a data-theme=’dark’ set of colors to be able to switch the values of these color variables.

For example

:root {
  --primary-color: rgb(255, 92, 92);
  --on-primary: rgb(250, 250, 250);
  --on-background: rgb(66, 66, 66);
}

[data-theme="dark"] {
  --primary-color: rgb(150, 65, 255);
  --on-primary: #000;
  --on-background: rgba(255, 255, 255, 0.9);
}

In the example above, we are using a checkbox and the checked attribute to set this attribute on the document allowing for us to dynamically toggle between light mode and dark mode.

This is something I like to add to all of my professional projects because people have different preferences for how they view text and so improves the user experience.

How do you restore the default value of a property?

In CSS, you can restore the default value of a property using the initial, inherit, or unset keywords.

Initial

The initial keyword allows you to set the property to its default value, which is defined in the official CSS specifications. For example, the initial value of the display property is inline.

div {
  display: initial;
}

In the above code, the display property is set to its initial value inline, disregarding any value it may have inherited.

Inherit

The inherit keyword enables a property to inherit its value from its parent element. For example, if you have a paragraph inside a div and the div has a font size of 20px, the paragraph will also have a font size of 20px if you use inherit.

p {
  font-size: inherit;
}

In the code above, the paragraph font size is set to the inherited value from its parent element.

Unset

The unset keyword acts as either inherit or initial, depending on whether the property is inherited or not.

If the property is an inherited one, unset will behave like inherit, otherwise it acts as initial.

h1 {
  color: unset;
}

In the example above, the color of the H1 tag will be reset to its initial or inherited value, depending on whether or not the color is an inheritable property.

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

z-index is a CSS property that controls the vertical stacking order of elements on a web page.

For example

Have you ever played around with canva, and it asks you if you want to bring an element forward in a design, or move it backward?

z index

It’s the same concept. The z-index is what controls how far forward or back it is.

Right now in my image, I can only bring the photo forward, as it's currently in the furthest back position. (So that it sits slightly behind the gray section and text).

Simple right?

A higher z-index value means the element will be closer to the front, and a lower value means it'll be further back. (While elements with the same z-index values stack up based on their order in the HTML file).

However, the z-index property only works on positioned elements. So to use z-index, an element must have a position value other than the default static. (The position can be relative, absolute, fixed, or sticky).

Here is how it looks in practice:

.header {
  position: relative;
  z-index: 2;
}
.main-content {
  position: absolute;
  z-index: 1;
}

What is cascading in CSS?

"Cascading" is a fundamental concept in CSS and is part of the reason why CSS is called Cascading Style Sheets.

It refers to the process of combining various style rules and resolving conflicts between them based on a system of precedence.

In the context of CSS, "cascading" denotes the process of determining which specific style rules apply to certain HTML elements when more than one rule could apply. It arranges them by their importance and sources in a "cascade".

A key aspect of cascading is the order of precedence. The order goes as follows:

  1. Importance: !important rules overrule others, regardless of source or order
  2. Specificity: If the importance is the same, the rule with more specific selectors takes precedence. For example, an ID selector overrules a class selector, and a class selector overrules a type selector
  3. Source Order: If both importance and specificity are equal, the rule that comes last in the source code will be applied

For example

/* Embedded style in .html file */
p {
  color: blue;
}

/* External style in .css file */
p {
  color: green;
}

/* Inline style in .html file */
<p style="color: red;">Hello World</p>

In this example, the text color of the paragraph will be red.

Even though the styles are equally specific (all targeting the p element), the inline style is applied due to its position in the cascading order.

In essence, cascading in CSS is a mechanism to maintain consistency, resolve conflicts between multiple style rules, and ensure that the most appropriate style is applied to each HTML element. This is a fundamental aspect of CSS that is important to master, especially when you end up working with multiple stylesheets.

When does DOM reflow occur?

DOM reflow refers to the process in which the browser recalculates the positions and geometries of elements in the document, for the purpose of re-rendering part or all of the document.

Basically, it’s the browser figuring out the layout of the page whenever a change occurs that can affect the positioning of elements.

DOM reflow can occur as a result of:

  1. Adding, removing, updating DOM nodes
  2. Applying a CSS style dynamically (such as element.style.width = "50%")
  3. Resizing the window or changing the orientation of a mobile device
  4. Calculating an element’s offsetWidth, offsetHeight, or any CSS property that requires layout information
  5. Activating CSS pseudo-classes such as :hover

This is an important concept to understand and build around, because DOM reflow is a costly operation performance-wise and can lead to sluggish performance if not managed properly.

This is because it involves the browser going through multiple steps as it calculates styles, builds the render tree, lays out the page, and repaints the elements, every time that it happens.

For example

Here’s a code snippet illustrating a forced reflow:

var container = document.getElementById('container');
container.style.display = 'inline-block';

The above JavaScript code will cause a reflow as it's updating the display property of an element.

Bearing in mind the performance implications, it's generally a good practice to batch style changes or to handle manipulations offscreen before applying them to the DOM to minimize reflow and repaint events.

Can you name the four types of @media properties?

The @media rule, used in media queries, allows different styles to be applied depending on the output device. There are four main types of media types in CSS:

  1. All: Applies to all devices
  2. Screen: Applies to screens (computers, tablets, smart-phones etc)
  3. Print: Applies to printers or documents viewed in print preview mode
  4. Speech: Applies to screen readers that "read" the page out loud

But beyond these types, you can also target widths and heights of screens to create responsive designs.

For example

Traditionally, for a vertical smartphone the width is less than 600px and this media query will apply the styles within it if the screen width is less than 600px.

@media screen and (max-width: 600px) {
  body {
	background-color: lightblue;
  }
}
media queries example

In this example, the body background color will change to light blue when the width of the viewport is 600 pixels or less, as long as the medium is a screen.

If you happen to be looking at a print preview that happened to be less than 600px it would not match the above media query.

Understanding media queries is crucial for responsive design. In fact, I would encourage you to practice resizing your window or using device emulation in the browser tools.

Go ahead and try to match the most common screen sizes for large monitors, laptops, large tablets, large smartphones, small smartphones, both in vertical and horizontal orientation, so you get broad experience with each.

Is it important to test your new webpage in different browsers?

Absolutely!

Cross-browser testing is of paramount importance in web development for multiple reasons.

Different browsers have different rendering engines

Each web browser has its own rendering engine (like Gecko for Firefox, or Blink for Chrome) that interprets the web page.

Because these engines sometimes interpret code differently, the same webpage might look or behave differently across browsers.

Consistent user experience

Your user base is likely to be spread across various browsers, including Chrome, Firefox, Safari, and even legacy browsers like Internet Explorer.

Testing across different browsers ensures a consistent user experience for all.

Not only that, but you can make sure that everything is working properly in each browser. (So many companies lose sales, simply because they don’t test features on different browsers, and their audience can’t purchase due to site issues).

Not every browser handles every new feature

Web technologies progress rapidly, and browsers often differ in the extent to which they adopt these new features.

By testing your website in different browsers, you can ensure that you have adequate fallbacks or polyfills in place for features not supported in certain browsers.

For example

/* CSS feature detection */
@supports (display: grid) {
	div {
    	    display: grid;
	}
}

In the above CSS snippet, the @supports rule is used to apply a CSS Grid layout only if the browser supports it.

(You can also use a website like https://caniuse.com/?search=grid in order to search a property and see which browsers support it.)

What are the limitations of CSS?

While being a powerful tool for web styling, CSS does come with its own set of limitations:

Browser compatibility

A key challenge when working with CSS is ensuring that the website looks and functions the same across all browsers.

Different browsers interpret CSS in slightly different ways, leading to inconsistencies. This is most noticeable when using a browser like Firefox which is not Chrome-based like Chrome and Edge.

Global scope

CSS has a global scope, meaning that a style declaration made in one part of the CSS file can impact elements across the entire website.

Although this can be helpful, it can also lead to unintentional design modifications if not managed carefully.

For example

/* CSS code demonstrating global scope */
h1 {
	color: blue;
}

This segment of CSS code sets the color of all elements across the entire website to blue.

This can be a problem especially when you’re using a CSS library like Bootstrap that has a number of default styles that will be applied to everything and you’ll need to override them to customize them in some cases.

Be aware of sequencing

The sequence in which styles are applied in a stylesheet matters due to CSS's cascading nature. This can lead to unexpected results and can be tricky to manage in large projects.

Depending on the order you’re referencing your stylesheets, you can get very different results, you should always have your custom stylesheet last if you are using external stylesheets or libraries.

Intermediate CSS interview questions

How does absolute positioning work?

Absolute positioning removes an element from the normal document flow and positions it based on its closest positioned ancestor.

When an element is absolutely positioned, it can be placed anywhere within its containing element using the top, bottom, left, and right properties. If no positioned ancestor is found, it takes the document body as the containing element.

For example

.relative {
  position: relative;
}

.absolute {
  position: absolute;
  top: 20px;
  right: 0;
}
absolute position

In the example above, the .absolute element is positioned 20 pixels from the top and right at the edge of its closest positioned ancestor, which in this case is the .relative element.

This approach provides more precise control over the layout, especially when creating complex designs or interactive components with CSS.

I find this technique most useful when I need to layer elements, like buttons or navigation over top of everything else on the page.

What are contextual selectors?

Contextual selectors in CSS allow you to select and style elements based on their relationship in the Document Object Model (DOM) hierarchy. They give you control over the application of styles to specific elements depending on their context.

There are three types of contextual selectors, and I’ll break each of them down below.

Descendant selectors (space)

This selector matches all elements that are descendants of a specified element.

body p {
  color: red;
}

This will apply to all <p> elements inside <body> tags—not just direct children, but all descendants.

Child selectors (>)

This selector matches all elements that are direct children of a specific element.

div > p {
  color: blue;
}
child selectors

This will only apply to <p> elements that are direct children of a <div>, not to <p> elements that are deeper descendants.

Adjacent sibling selectors (+)

This selector matches all elements that are immediately preceded by a certain element.

h1 + p {
  color: green;
}
Adjacent sibling selectors

This will apply to any <p> element that directly follows an <h1> element.

TL;DR

Contextual selectors are great for allowing you to create complex styles based on the structure of your HTML.

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

The nth-child() and nth-of-type() selectors help in achieving complex selection patterns without adding extra classes or ids.

Though they seem similar, they have some crucial differences that might affect how they behave in your CSS rules.

nth-child()

The nth-child(n) selector matches elements based on their position in a group of siblings. It counts all elements, regardless of type, and applies styles to the nth child.

For example

/* Selects 3rd child element irrespective of its type */
:nth-child(3) {
  color: red;
}

This will select the third child element, regardless of whether it's a <p>, <div>, or <span>, and change the text color to red.

nth-of-type()

The nth-of-type(n) selector, on the other hand, first looks at the type of the element and then matches based on its position amongst other similar elements.

It applies styles to the nth element of its type.

For example

/* Selects the 3rd p element */
p:nth-of-type(3) {
  color: blue;
}

This rule will only select the third <p> element, skipping other types of elements, and change the text color to blue.

nth-of-type

Put simply, nth-child() looks at the position in the whole sibling group, while nth-of-type() only counts similar elements.

So when you're dealing with a group of different element types and only want to target a specific one, nth-of-type() might be the better choice.

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

In CSS, it's possible to automatically number the heading values of sections and categories using counters and the content property.

CSS counters are, in essence, variables maintained by CSS whose values can be incremented by CSS rules to track how many times they're used.

For example

body {
    counter-reset: section;
}

h1 {
    counter-increment: section;
}

h1:before {
    content: "Section " counter(section) ": ";
}

Let's walk through the code and what's happening here:

First, you need to initialize the counter using the counter-reset property in your CSS, usually in a parent element, like so:

body {
	counter-reset: section;  /* Set a counter named 'section', and its initial value is 0. */
}

Next, for every heading you want to number, you'd use the counter-increment property to increase the counter:

h1 {
	counter-increment: section;  /* Increment the counter by 1 */
}

Finally, you can use the content property to insert the value of the counter before or after the content of the headings:

h1:before {
	content: "Section " counter(section) ": ";
}

In this example, every h1 element will be numbered as 'Section 1:', 'Section 2:', 'Section 3:', etc, automatically by CSS.

automatically number sections

Remember, CSS counters are not limited to integer numbers. They can also be used with roman numbers or alphabets by specifying a list-style-type as a second parameter to the counter() function.

For example

h1:before {
	content: counter(section, upper-roman) ". ";
}

Now, this will number the sections as 'I.', 'II.', 'III.', etc instead.

This technique is incredibly useful when you're dealing with content that moves around a bit. It saves you from manually numbering (and renumbering) every section yourself.

What is the use of box-shadow in CSS and how is it different from using a drop-shadow?

The box-shadow property in CSS is used to add shadow effects around an element's frame. It allows you to set the color, offset, blur, and spread of the shadow, either inside or outside the box.

The structure of the box-shadow property is as follows:

box-shadow: [horizontal offset] [vertical offset] [blur radius] [optional spread radius] [color];
  • Horizontal offset (required): How much horizontal shadow you want. Positive numbers will push the shadow right, and negative numbers will push it left
  • Vertical offset (required): How much vertical shadow you want. Positive numbers push the shadow down, negative numbers push it up
  • Blur radius (optional): The bigger the number, the more blur, so the shadow becomes bigger and lighter
  • Spread radius (optional): Positive numbers increase the size of the shadow, negative numbers decrease the size. Default is 0 (the shadow is the same size as the element)
  • Color (required): The color of the shadow.

For example

.box {
  box-shadow: 5px 10px 15px 0 rgba(0, 0, 0, 0.3);
}
shadow box

This will render a shadow that is offset 5 pixels to the right and 10 pixels down, has a blur radius of 15 pixels and a black color with 30% transparency.

The box-shadow property is actually quite versatile and can create a variety of effects, such as multiple shadows, inner shadows, and even fancy effects like glowing or neon text on a container element.

It’s something I use almost all the time in order to give some visual depth to different containers and sections within my projects. Remember to test your design in different browsers to ensure your shadows appear as expected, as CSS effects can sometimes vary.

filter: drop-shadow

There is a big difference between box-shadow and filter: drop-shadow as seen below.

For example

.drop-shadow {
  filter: drop-shadow(5px 10px 15px rgba(0, 0, 0, 0.3));
}
drop shadow

In this example, we are using the same image for both elements, on the left we are using our box-shadow which is adding shadow to the container, and drop-shadow on the right element which allows for shadow within the image and without the container being highlighted.

Both ways of implementing shadow can be very useful, as I said I mostly use box-shadow, but if I had a transparent png, like a logo in this case, drop-shadow is a great way to highlight it and give it some more depth.

How would you style an image or element to have rounded corners?

To give an image or element rounded corners in CSS, you can use the border-radius property. It sets the radius of the corner curve, and you can specify one value to make all corners the same, or multiple values to give each corner a different radius.

For example, to give an image element a border radius of 10 pixels, you'd write:

img {
  border-radius: 10px;
}
same radius

All four corners will be rounded with the same 10-pixel radius, creating a consistent, oval-like edge around the image.

Or, if you want to specify each corner individually, you can provide four values (top-left, top-right, bottom-right, bottom-left):

img {
  border-radius: 10px 20px 30px 40px;
}
variable radius

This will give the top-left corner a 10-pixel radius, the top-right a 20-pixel radius, the bottom-right a 30-pixel radius, and the bottom-left a 40-pixel radius.

Alternatively, if you'd like a perfect circle or a pill-like shape for your image or element, you can use a border-radius of 50%.

img {
  border-radius: 50%;
}
circular radius

Remember that the element should have equal width and height to form a perfect circle with this method, or else it will be a pill-shape.

Rounded corners can help soften the look of an image or element and blend it more naturally into your design. I would recommend almost always using border-radius on all containers in your projects to instantly and easily establish a professional look.

What is the overflow property in CSS used for?

The overflow property in CSS deals with the content of block-level elements when it overflows its boundaries i.e., when it's too big to fit in its computed box.

There are four values for the overflow property:

  • visible: This is the default value and it means that the content is not clipped and it renders outside the element's box
  • hidden: If the content is overflowing, it will be hidden
  • scroll: This will cause a scrollbar to appear whether it's needed or not
  • auto: This is somewhat a combination of visible and scroll. It will render a scrollbar only when the content is overflowing
.overflow-visible {
	overflow: visible;
}
overflow visible
.overflow-hidden {
	overflow: hidden;
}
overflow hidden
.overflow-scroll {
	overflow: scroll;
}
overflow scroll
.overflow-auto {
	overflow: auto;
}
auto overflow

The overflow property is applied per direction (left and right or top and bottom) and can therefore be used to manage overflows in the horizontal direction (overflow-x) or the vertical direction (overflow-y).

For example

.overflow-x {
	overflow-x: scroll; /* Horizontal Scroll */
}
overflow x scroll
.overflow-y {
	overflow-y: auto; /* Vertical Scroll when Needed */
}
auto overflow vertical scroll

Handling overflowing content properly ensures a better user experience, as it can prevent unexpected layout behavior and make your design look more polished and intentional.

What is the importance of CSS Sprites?

CSS sprites are a technique in web design where a number of images are combined into a single image file to reduce server requests and save bandwidth.

This is significant because every additional server request increases the time it takes for your webpage to load.

Here's the basic concept:

  • You have a collection of images that you want to use on a website
  • Instead of leaving them as individual images, you combine them all into one large image (this is your sprite sheet)
  • When a specific image is needed, you use CSS to only display the portion of the image that contains the relevant image

Here is a sample code snippet from CSS Tricks that can be used to implement a sprite:

For example

.flags-canada, .flags-mexico, .flags-usa {
  background-image: url('../images/flags.png');
  background-repeat: no-repeat;
}

.flags-canada {
  height: 128px;
  background-position: -5px -5px;
}

.flags-usa {
  height: 135px;
  background-position: -5px -143px;
}

.flags-mexico {
  height: 147px;
  background-position: -5px -288px;
}
css sprite images

In this example, the background image value is set for the 3 flag classes.

Each flag related class then defines the height, and location (using background-position) of each flag within the sprite sheet. The first value represents the horizontal value, and the second represents the vertical value.

Why use CSS sprites?

An important aspect of CSS sprites is that even though your entire sprite sheet might be large, because you're only showing a small section of it at any given time, you can actually save on load time.

The use of CSS sprites leads to fewer HTTP requests, reduced server load, and faster page load times, especially on websites that use many small images or icons.

Furthermore, a key advantage of CSS sprites is the ability to keep images in a centralized 'spritesheet'. It simplifies site maintenance when all your images are consolidated into a few files.

However, on the downside, CSS sprites can be more complex to implement and maintain than individual images. But as a CSS developer, they're a useful tool to have in your optimization arsenal.

CSS Sprites are a crucial part of website optimization, and although they might seem a bit strange at first, once you get the hang of them, they can make a big difference in the performance of your site.

What is tweening in CSS?

Tweening, short for ‘in-betweening’, is an animation technique used to create smooth transitions from one state to another over time.

So, in the context of CSS, tweening refers to intermediate property keyframes that are automatically calculated by the browser to create a smooth animation effect. This typically involves changes in size, position, color, and other properties of an element.

Good news?

By default, CSS animations and transitions perform tweening for you, so when you specify keyframes or the start and end states of a transition, the browser will calculate and render the in-between frames.

For example

a {
  color: #0f1a23;
  box-shadow: inset 0 0 0 0 #1e2c3a;
  transition: 
    color .3s ease-in-out, 
    box-shadow .3s ease-in-out, 
}

a:hover {
    color: #fff;
    box-shadow: inset 300px 0 0 0 #1e2c3a;
}
transition

In this case, when you hover over the <a> element, it will smoothly transition the box-shadow and font color over the course of 0.3 seconds.

The 'tweened' frames here are the width of the shadow and color difference at every fraction of a second between the start and end of the transition.

You can also modify the acceleration of this tweening by changing the timing function, in this case we are using ease-in-out, which starts slowly, speeds up in the middle and slows down again at the end. You could also use ease, linear, ease-in, ease-out, among others to adjust how the transition looks.

What is the grid system?

The grid system in CSS is a way to create flexible and responsive web layouts. It allows for the arrangement of HTML elements into rows and columns, much like a table but far more flexible.

The CSS Grid Layout Module offers a grid-based layout system, with rows and columns, much like a spreadsheet. It allows developers to lay out web pages quickly and intuitively, with a high degree of control over the positioning, sizing, and alignment of elements.

For example

Here's a simple example of using CSS grid:

.container {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr; // creates three equal columns
}

.item {
  grid-column: 1 / 3; // the item will span the first two columns
}
css grid

In this example, we have a container with three equally wide columns, and an item that spans the first two columns. On the row below, by default the other items will each fill one of the 3 equal columns.

CSS Grid works well with other layout methods like Flexbox, and can be used to create complex, responsive designs with less code compared to traditional methods.

Speaking of which…

What are the properties of flexbox?

Flexbox, or the Flexible Box Layout, is a layout model that allows easy manipulation of the dimensions and order of boxes in CSS. It's designed for one-dimensional layouts and is fantastic for aligning elements within a container.

Here are some of the key properties in Flexbox:

display

This property is set to flex to generate a flex container. It's the first step in using the Flexbox model.

.container {
 display: flex;
}
flexbox

flex-direction

This influences the direction in which the flex items are placed in the flex container. It accepts values such as row, row-reverse, column, and column-reverse.

In the example below, row-reverse layouts out elements right to left.

.container {
 flex-direction: row-reverse;
}
flexbox reverse direction

align-items

This property aligns flex items along the cross axis. It accepts values like stretch, flex-start, flex-end, center, baseline. In this example, items start at the left of the container and flow right.

.container {
 align-items: flex-start;
}
flexbox start

justify-content

This property aligns flex items along the main axis of the current line of the flex container.

It accepts values like flex-start, flex-end, center, space-between, space-around.

For example

This example uses space-around to put an even space on the left and right of each element.

.container {
  justify-content: space-around;
}
justify content

flex-wrap

By default, flex items will all try to fit onto one line. You can change that with the flex-wrap property. It accepts values like nowrap, wrap, and wrap-reverse.

You can see here that our items flow nicely onto a second line.

.container {
 flex-wrap: wrap;
}
flexwrap

flex-grow, flex-shrink, and flex-basis

These are properties that you apply to individual flex items rather than the container.

  • flex-grow defines what amount of the available space inside the flex container the item should take up
  • flex-shrink defines the ability for a flex item to shrink if necessary, and
  • flex-basis defines the default size of an element before the remaining space is distributed

In the following code, we can see that each item fills the space available.

.item {
  flex-grow: 1;
  flex-shrink: 2;
  flex-basis: auto;
}
flexgrow

What is the difference between CSS grid and flexbox?

Both CSS Grid and Flexbox (Flexible Box) are powerful layout systems available in CSS, and they each offer unique strengths and use cases.

CSS grid

CSS grid is a two-dimensional layout system that gives you control over items in rows as well as columns. It’s incredibly helpful when you want to design a complex web layout consisting of panels and grids.

With CSS Grid, you can easily create a grid system as per your needs and it comes handy when you're dealing with a larger, more complex web layout where you need control both horizontally and vertically.

For example

Suppose you're designing a magazine layout where items need to be placed in a certain way both vertically and horizontally. In such scenarios, CSS Grid will really shine.

.container {
	display: grid;
	grid-template-columns: 200px auto 200px;
	grid-template-rows: 150px auto 50px;
}
css grid layout

In the above example, we are declaring a grid with three columns (widths: 200px, automatic, and 200px) and three rows (heights: 150px, automatic, and 50px). The automatic value will fill whatever space is remaining in this case.

Flexbox

Flexbox on the other hand, is a one-dimensional layout method for laying out items in rows or columns.

It allows you to align and distribute space within a container. This means it can seem more straightforward than CSS Grid, but it can only deal with one dimension at a time — either as a row or as a column.

Flexbox is extremely handy in terms of creating a responsive interface, or when you want items to stretch and shrink to fit into their containers.

For example

.container {
	display: flex;
	justify-content: space-between;
}
flexbox example

In the example above, we are declaring a flex container and the items will be evenly distributed along the horizontal line.

TL;DR

CSS Grid is better for complex, two-dimensional layouts, while Flexbox is ideal for simpler, one-dimensional layouts. You can even use them in combination to build flexible and robust layouts.

How does `calc() work?

In CSS, the calc() function serves as a way to perform calculations that are used to determine the values of CSS properties. It can be used wherever length values (those that accept units such as px, %, em, etc.) are allowed.

The calc() function supports addition, subtraction, multiplication, and division.

For example

You could use the calc() function to create a two-column layout where one column is 200px wide, and the other takes up the remainder of the space:

#main {
	width: calc(100% - 200px);
}

#sidebar {
	width: 200px;
}
calc layout example

In this example, the width of the main area is calculated as 100% of the parent minus 200 pixels, which is the width of the sidebar.

The calc() function is really powerful because it lets you keep some parts of your layout size flexible while controlling other parts precisely. It's often used for things like creating fluid grids and proportional columns and it is a potent tool for responsive designs.

.element {
	padding: calc(1em - 2px);
	width: calc(100%/3 - 2rem);
}
calc column example

In the example above, the padding of the element is calculated as 1em minus 2 pixels, and the width is calculated as one-third of the parent's width minus 2rem. As you can see, we can chain multiple calculations within the calc() function.

Remember, there must be spaces around the "+" and "-" operators, or else calc() will not work. Multiplication and division operators don’t require spaces, but they can help readability.

TL;DR

calc() is a powerful CSS function that allows you to perform mathematical operations within your stylesheets. It adds a new level of flexibility to your toolbox for crafting sophisticated and dynamic designs.

I personally use this when I want to have something be the width of a page minus the width of padding or margin or something like that.

What do CSS Custom properties variables mean?

CSS Custom Properties, often referred to as CSS Variables, are entities that contain specific values to be reused throughout your document.

They are set using custom property notation (i.e., --main-color: black;).

Once you have set a CSS variable, you can use it elsewhere in your code by invoking it with the var() function.

For example

/* Define our custom property */
:root {
  --main-color: dodgerblue;
}

/* Use our custom property */
body {
  background-color: var(--main-color);
}

In the example above, --main-color is the CSS custom property, and it is set to dodgerblue. Then, using the var() function, we can insert the value of this custom property as the value for background-color in the body selector.

TL;DR

The key advantage of using CSS variables is the ease in which they offer changing multiple CSS properties' values. This is particularly handy when dealing with themes or wanting to make site-wide changes to a certain color, padding, etc.

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

CSS variables and preprocessor variables such as those in SASS, LESS, and Stylus, are both tools to store reusable values. However, they do differ in significant ways.

CSS variables

CSS variables, officially called "CSS Custom Properties," are native to CSS and don't require a preprocessor. This means they can be manipulated using JavaScript and are scoped, meaning you can set them globally or locally.

Preprocessor variables

Preprocessor variables, on the other hand, are a feature of CSS preprocessors like SASS, LESS, and Stylus.

They are not native to CSS and hence need to be compiled into regular CSS. Also, they cannot be manipulated with JavaScript and they aren't scoped in the same way as CSS variables.

TL;DR

While both types of variables provide ways to store reusable values, CSS variables offer more flexibility and control. This is due to their ability to be manipulated live in the browser and their scope control.

This is more beneficial for being able to have a dynamic theme, like the ability to switch between light and dark mode.

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

The translate() function in CSS is used to reposition an element in the 2D space without interfering with the normal flow, and is part of the CSS transform property.

While absolute positioning is a method that takes the element out of the normal document flow, and positions it relative to its nearest positioned ancestor.

The advantages of using translate() over absolute positioning include:

  • Performance: Transforms are hardware-accelerated in modern browsers, which can lead to smoother animations
  • Flow: Unlike absolute positioning, transforming an element doesn't affect the flow of the document. Other elements aren't repositioned to fill the gap
  • Complex animations: Transforms can be combined with other functions (e.g., rotate, scale) to create more complex animations

For example

div {
  transform: translate(50px, 100px);
}
translated positioning

In the example above, the div is repositioned 50 pixels to the right and 100 pixels down from its original position.

What are the differences between adaptive design and responsive design?

Adaptive design and responsive design are both approaches to designing web layouts that work well on a variety of devices, but they have fundamental differences in how they adapt to different screen sizes.

Responsive design

Responsive design is fluid and flexible. It uses CSS media queries to adjust the layout and resize content based on the width of the browser window.

The same design is served to all devices, but it "responds" to the viewport size and changes accordingly.

For example

.container {
  width: 80%;
}

@media screen and (max-width: 600px) {
  .container {
	width: 100%;
  }
}
responsive design

This CSS makes the .container element take up 80% of the window's width by default, but on screens narrower than 600 pixels, it'll take up the full width.

Adaptive design

Adaptive design on the other hand, uses predefined layouts that have been created for specific screen resolutions. The server detects the user's device type and screen size and delivers the appropriate layout.

It's more rigid than responsive design but can provide a more tailor-made experience for specific devices.

For example

.adaptive-container {
  width: 60%;
}
adaptive design

Both approaches have their merits and challenges and can achieve similar results:

  • Responsive design can be more fluid and seamless, but it may require more testing and tweaking to ensure content looks good at any size
  • Adaptive design can offer a more optimal user experience on specific devices, but it requires more work upfront to create the different layouts, and it may not cover all possible devices and screen sizes

Your choice between responsive and adaptive design will depend on your project's requirements, your target audience, and the devices they're using.

Explain the difference in approach when designing a responsive website over a mobile-first strategy?

Responsive web design and mobile-first design are both strategies for creating websites that work well on a range of devices, from desktops to mobile phones. However, they differ in their starting points and design philosophy.

Responsive web design begins with the desktop version of a site and then uses CSS media queries to adjust the layout and content as the viewport gets narrower.

.container {
  width: 1000px;
}

@media screen and (max-width: 600px) {
  .container {
	width: auto;
  }
}
responsive design section

This is a responsive design. The .container element has a fixed width for large screens, but on screens narrower than 600 pixels, it becomes fluid.

Mobile-first design, on the other hand, starts with the mobile version of the site and then uses CSS media queries to progressively enhance the layout as the viewport gets wider.

It's a subset of responsive design, also known as "progressive enhancement."

.container {
  width: auto;
}

@media screen and (min-width: 600px) {
  .container {
	width: 1000px;
  }
}
mobile first design section

This is a mobile-first design.

The .container element is fluid by default, appropriate for a mobile view, but on screens wider than 600 pixels, it adopts a fixed width more suited to a desktop view.

The choice between responsive design and mobile-first design often depends on your audience and their device usage. If a significant portion of your users are on mobile, a mobile-first approach can ensure a great user experience for them.

Not to mention, a mobile-first approach can improve overall site performance, as it prioritizes loading only the necessary content for smaller screens.

For me personally, I usually start with desktop first design because the layout is more complicated as it has the ability to spread out more on the page. Whereas on mobile, everything basically flows in one column in most cases.

You can see from our example images that you can achieve the same end result with either approach and it is more a matter of preference. Just remember though like I said earlier. It is important to remember to conduct thorough cross-browser testing in different viewports to ensure that your website looks good and functions well in all scenarios.

Intermediate CSS interview questions

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

There are a few options, which I’ll break down in a second.

However, I will say that the process of matching CSS selectors against elements in the document is fundamental to how browsers render web pages, which is why it's so important to understand.

Right-to-left parsing

Contrary to how people read in western countries, browsers parse CSS selectors from right to left.

So, if you have a selector like div p span, the browser first selects all span elements, then it navigates up to find the span elements that are descendants of p, and among those, it finally keeps the span elements that are also descendants of a div with the ‘.container’ class.

For example

div.container p span {
  color: blue;
  font-weight: bold;
}
right to left parsing

In the above code snippet, it will select all span elements nested inside a p tag, which is then inside a div with the class ‘container’, and turn their text color to blue and bold.

Matching algorithm

The browser starts by checking the type, class, id, and other attributes of an element against the CSS rule. If it finds a match, it applies the CSS rule to that element.

In case of multiple matches, it follows the CSS specificity and inheritance rules to resolve the conflicts.

Browser optimization

Browsers use various optimization methods to speed up the process. They often categorize CSS rules and skip whole groups of selectors if they don’t apply to a particular element.

Understanding this matching process is crucial in optimizing performance and creating efficient CSS selectors. You want to be as specific as you need to without having to be too specific, if you can write a selector for all spans that satisfies your needs, that is better than targeting spans that are children of div and paragraph elements.

What does !important mean in CSS?

The !important rule in CSS is a way to make your CSS rule take precedence over other later rules in your CSS. In essence, it gives a CSS rule higher importance than regular rules.

It's expressed after the value, like so:

<p class="text-color">Here is some text with color !important</p>
p {
  color: blue !important;
}

.text-color {
  color: red;
}
!important in css

In this example, the !important rule ensures that all paragraphs will indeed be blue, even with the more specific rule targeting the class ‘text-color’.

However, using !important should be avoided when possible because it makes debugging more difficult by breaking the natural cascading in your stylesheets.

It's generally better to use more specific selectors to target the elements you want to style, or when you’re using other stylesheets from other frameworks that you want to overwrite.

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

In a normal flow, a web browser will discover, download, and parse all linked CSS files in the order they appear in the HTML document.

So, in a scenario where style1.css appears before style2.css in your HTML document, style1.css would indeed be downloaded and parsed before style2.css starts downloading.

For example

<head>
  <link rel="stylesheet" href="style1.css">
  <link rel="stylesheet" href="style2.css">
</head>

Understanding this is crucial because it can impact the perceived load time of your webpage.

If style1.css is very large, it may block the rendering of your page as the browser waits for it to download and parse before it even starts on style2.css.

A potential solution to manage this more effectively, is to split your CSS into critical and non-critical parts. You could inline the critical CSS in the <head> of your HTML document and load the non-critical CSS asynchronously or defer its load until the critical CSS has finished loading.

So how did you do?

So there you have it - 50 of the most common CSS ( + some HTML) interview questions that you might face during a frontend developer interview.

Did you answer all 50 correctly? Congratulations! You’re ready to ace that interview.

Or did you struggle with some of them? If you knew the answers but forgot, just give yourself some time to recap before the interview.

Or did none of this make sense? Not a problem either.

Remember I said earlier, that if you struggle to understand any of the questions in this guide, or want to improve your current skills, then check out my complete CSS digital bootcamp.

learn CSS

You’ll learn everything from CSS basics to advanced CSS techniques by completing 100+ exercises and 10 projects.

This course will help you learn how to use CSS to create beautiful, responsive websites that wow users and employers. Become a CSS Pro and never create an ugly website again.

You’ll not only get access to step-by-step tutorials, but you can ask questions from me and other instructors, as well as other students inside our private Discord.


Either way, if you decide to join or not, good luck with your interview and go get that job!

More from Zero To Mastery

How To Become A Web Developer (From Complete Beginner to Hired) preview
How To Become A Web Developer (From Complete Beginner to Hired)

Want to become a Web Developer but not sure how? Our step-by-step guide shows you how to go from beginner to hired (without wasting $1,000s on a bootcamp or degree). And we answer all your FAQ.

CSS vs HTML: Comparison Guide (With Code Examples) preview
CSS vs HTML: Comparison Guide (With Code Examples)

HTML vs CSS. Learn their differences, pros, and cons, and how to use them with different variables for dynamic site creation!

Beginners Guide To Flexbox With Bootstrap preview
Popular
Beginners Guide To Flexbox With Bootstrap

Learn how to use Flexbox features for responsive design inside of Bootstrap. I've also included some code examples to show you how easy it is to start using!