CSS Interview Questions

30+ CSS interview questions and answers in quiz-style format, answered by ex-FAANG interviewers
Questions and solutions by ex-interviewers
Covers critical topics

Looking to ace your next CSS interview questions? You’re in the right place.

CSS interview questions test your core styling expertise. Interviewers typically focus on topics such as:

  • Specificity & Cascade: Understanding how CSS rules compete and how to control which styles win.
  • Box Model: Mastering content, padding, border, and margin to build precise layouts.
  • Flexbox & Grid: Creating flexible, responsive layouts with modern CSS layout systems.
  • Responsive Design: Making designs adapt gracefully across screen sizes using media queries and fluid units.
  • Selectors & Combinators: Targeting elements efficiently with class, attribute, pseudo-class, and pseudo-element selectors.
  • Performance & Optimization: Writing lean, maintainable CSS and minimizing repaint/reflow overhead.

Below, you’ll find 30+ curated CSS interview questions, covering everything from foundational concepts to advanced layout and optimization strategies. Each question includes:

  • Quick Answers (TL;DR): Concise responses to help you answer on the spot.
  • Detailed Explanations: In-depth insights to ensure you understand not just the “how,” but the “why.”

These questions are crafted by senior and staff engineers from top tech companies—not anonymous contributors or AI-generated content. Start practicing below and get ready to stand out in your CSS interview!

If you're looking for CSS coding questions -We've got you covered as well, with:
Javascript coding
  • 40+ CSS coding interview questions
  • An in-browser coding workspace that mimics real interview conditions
  • Reference solutions from ex-interviewers at Big Tech companies
  • One-click automated, transparent test cases
  • Instant UI preview for UI-related questions
Get Started
Join 50,000+ engineers

Explain your understanding of the box model and how you would tell the browser in CSS to render your layout in different box models.

Topics
CSS

The CSS box model describes the rectangular boxes that are generated for elements in the document tree and laid out according to the visual formatting model. Each box has a content area (e.g. text, an image, etc.) and optional surrounding padding, border, and margin areas.

The CSS box model is responsible for calculating:

  • How much space a block element takes up.
  • Whether or not borders and/or margins overlap, or collapse.
  • A box's dimensions.

Box model rules

  • The dimensions of a block element are calculated by width, height, padding, and border.
  • If no height is specified, a block element will be as high as the content it contains, plus padding (unless there are floats — see describe floats and how they work).
  • If no width is specified, a non-floated block element will expand to fit the width of its parent minus the padding, unless it has a max-width property set, in which case it will be no wider than the specified maximum width.
    • Some block-level elements (e.g. table, figure, and input) have inherent or default width values and may not expand to fill the full width of their parent container.
    • span is an inline-level element and does not have a default width, so it will not expand to fit.
  • The height of an element is calculated by the content's height.
  • The width of an element is calculated by the content's width.
  • By default (box-sizing: content-box), padding and border are not part of the width and height of an element.

Extra

Look up the box-sizing property, which affects how the total heights and widths of elements are calculated.

  • box-sizing: content-box: This is the default value of box-sizing and adheres to the rules above.

    For example:

    .example {
    box-sizing: content-box;
    width: 100px;
    padding: 10px;
    border: 5px solid black;
    }

    The actual space taken by the .example element will be 130px wide (100px width + 10px left padding + 10px right padding + 5px left border + 5px right border).

  • box-sizing: border-box: The width and height will include the content, padding and border (but not the margin). This is a much more intuitive way to think about boxes and hence many CSS frameworks (e.g. Bootstrap, Tailwind, Bulma) set * { box-sizing: border-box; } globally, so that all elements use such a box model by default. See the question on box-sizing: border-box for more information.

    For example:

    .example {
    box-sizing: border-box;
    width: 100px;
    padding: 10px;
    border: 5px solid black;
    }

    The element will still take up 100px on the page, but the content area will be 70px wide (100px - 10px left padding - 10px right padding - 5px left border - 5px right border).

Border and margin behavior

  • Borders do not collapse or overlap with those of adjacent elements. Each element's border is rendered individually.
  • Margins can collapse, but only vertically and only between block-level elements. Horizontal margins do not collapse. This means that if one block element has a bottom margin and the next has a top margin, only the larger of the two will be used. This behavior is independent of box-sizing and is the default in CSS.

References

What does `* { box-sizing: border-box; }` do?

What are its advantages?
Topics
CSS

* { box-sizing: border-box; } is a CSS rule that applies the box-sizing: border-box property to every element on a webpage, overriding the default content-box model. This changes how the width and height of elements are calculated, making the box model more predictable and intuitive by including padding and border in the specified dimensions.

Understanding the box model

The CSS box model defines how elements are rendered in terms of their dimensions and spacing. Every element is a rectangular box composed of:

  • Content: The actual content (text, images, etc.).
  • Padding: The space between the content and the border.
  • Border: The area surrounding the padding.
  • Margin: The space outside the border, separating the element from others.

The box-sizing property determines which parts of the box model contribute to an element’s width and height.

Default behavior: box-sizing: content-box

With content-box (the default), the width and height properties only account for the content area. Any padding or border added to the element increases its total size beyond the specified width or height. For example:

div {
box-sizing: content-box;
width: 100px;
height: 100px;
padding: 10px;
border: 5px solid black;
}
  • Content size: 100px × 100px
  • Total size: 100px (content) + 10px (left padding) + 10px (right padding) + 5px (left border) + 5px (right border) = 130px wide. Similarly, 130px tall.

This can lead to unexpected layout issues, as the element’s total size exceeds the specified dimensions.

box-sizing: border-box

With border-box, the width and height properties include the content, padding, and border. The content area shrinks to accommodate padding and border within the specified dimensions. Using the same example:

div {
box-sizing: border-box;
width: 100px;
height: 100px;
padding: 10px;
border: 5px solid black;
}
  • Total size: 100px × 100px
  • Content size: 100px - 10px (left padding) - 10px (right padding) - 5px (left border) - 5px (right border) = 70px wide. Similarly, 70px tall.

The margin is not included in the width or height calculation for either box-sizing value.

Comparison Table

Propertybox-sizing: content-box (default)box-sizing: border-box
ContentIncludedIncluded
PaddingExcludedIncluded
BorderExcludedIncluded
MarginExcludedExcluded

Advantages of box-sizing: border-box

  1. Intuitive sizing: Designers often think of an element's size holistically, including its padding and border. border-box aligns with this mental model, making it easier to create layouts where elements fit within predefined grid systems or containers.

  2. Simplified layout calculations: With border-box, you don't need to manually subtract padding and border values to calculate the content size. This reduces errors in responsive designs and complex layouts.

  3. Consistency across elements: Applying * { box-sizing: border-box; } globally ensures all elements (e.g. divs, inputs, images) behave consistently, preventing unexpected size increases when styling forms, buttons, or other components with padding or borders.

  4. Better integration with CSS frameworks: Popular frameworks like Bootstrap and Tailwind CSS use border-box by default to streamline development and ensure predictable layouts.

  5. Easier responsive design: In responsive layouts where percentages or viewport units (e.g. vw, vh) are used, border-box prevents elements from overflowing their containers due to added padding or borders.

  6. Improved form styling: Form elements like input and select often have browser-specific padding and borders. border-box ensures consistent sizing across browsers, making it easier to align form fields in a layout.

Practical example

Consider a layout with three columns, each intended to be 33.33% wide within a 900px container:

.container {
width: 900px;
display: flex;
}
.column {
width: 33.33%;
padding: 15px;
border: 2px solid black;
}
  • With content-box: Each column's total width becomes 33.33% + 15px (left padding) + 15px (right padding) + 2px (left border) + 2px (right border). This exceeds 33.33%, causing the columns to overflow or wrap unexpectedly.
  • With border-box: Each column's total width remains 33.33% (approximately 300px in a 900px container), with padding and borders fitting within that size. The content area adjusts to accommodate these additions.
* {
box-sizing: border-box;
}

This ensures the columns fit perfectly within the container without manual recalculations.

Additional Considerations

Performance implications

Using * { box-sizing: border-box; } has negligible performance impact, as it's a simple CSS property applied during rendering. However, the universal selector (*) can be slightly less performant on very large DOM trees due to its broad application. For optimization, you can apply box-sizing: border-box to specific elements or use a more targeted selector like:

html {
box-sizing: border-box;
}
*,
*:before,
*:after {
box-sizing: inherit;
}

This approach sets border-box as the default for all elements but allows specific elements to inherit or override it (e.g., revert to content-box if needed).

Browser support

The box-sizing property is universally supported across all modern browsers, including Chrome, Firefox, Safari, Edge, and Internet Explorer 8+. No vendor prefixes are required, making it safe for production use.

Edge cases and gotchas

  1. Legacy browser issues: While rare, older browsers like IE6-7 may not support box-sizing. If supporting these browsers is necessary, test layouts thoroughly or use fallbacks.
  2. Third-party components: Some third-party libraries or widgets may assume content-box. Applying border-box globally could break their styling, requiring overrides.
  3. Flexbox and Grid: In modern layouts using Flexbox or CSS Grid, border-box simplifies alignment by ensuring elements respect their container's constraints without unexpected overflows.
  4. Percentage-based padding: When padding is defined in percentages, it's calculated relative to the element's width (even for vertical padding). With border-box, this can reduce the content area more than expected, so test carefully.

When to use content-box

While border-box is generally preferred, content-box may be useful in specific scenarios:

  • Precise content sizing: When you need the content area to be exactly the specified width or height, regardless of padding or borders (e.g. for image galleries or canvas elements).
  • Legacy codebases: If a project was built with content-box assumptions, switching to border-box globally could break existing layouts.

Best practices

  1. Apply globally early: Set * { box-sizing: border-box; } at the start of your CSS to ensure consistency across your project.
  2. Use resets or Normalize.css: Many CSS resets (e.g. Normalize.css) include border-box by default. Verify your reset to avoid conflicts.
  3. Test with dynamic content: Ensure border-box works as expected with dynamically sized elements, such as those using min-width, max-width, or percentage-based dimensions.
  4. Document overrides: If you need to use content-box for specific elements, document the reason clearly to avoid confusion for other developers.

References

What is the CSS `display` property and can you give a few examples of its use?

Topics
CSS

The common values for the display property: none, block, inline, inline-block, flex, grid, table, table-row, table-cell, list-item.

display ValueDescription
noneDoes not display an element (the element no longer affects the layout of the document). All child elements are also no longer displayed. The document is rendered as if the element did not exist in the document tree.
blockThe element consumes the whole line in the block direction (which is usually horizontal).
inlineElements can be laid out beside each other.
inline-blockSimilar to inline, but allows some block properties like setting width and height.
flexBehaves as a block-level flex container, which can be manipulated using the flexbox model.
gridBehaves as a block-level grid container using grid layout.
tableBehaves like the <table> element.
table-rowBehaves like the <tr> element.
table-cellBehaves like the <td> element.
list-itemBehaves like a <li> element, which allows it to define list-style-type and list-style-position.

For a complete list of values for the display property, refer to CSS Display | MDN.

References

What is CSS selector specificity and how does it work?

Topics
CSS

When multiple CSS rules could apply to the same HTML element, the browser needs a way to decide which rule takes precedence. This is determined by the CSS cascade, which considers importance, inline styles, selector specificity, and source order. Selector specificity is a key part of this process, calculating a weight for each selector.

The browser determines what styles to show on an element depending on the specificity of the CSS rules that match it. Specificity is calculated for each rule to decide which one takes precedence.

How is specificity computed?

The specificity algorithm is basically a three-column value of three categories or weights — ID, CLASS, and TYPE — corresponding to the three types of selectors. The value represents the count of selector components in each weight category and is written as ID - CLASS - TYPE. The three columns are created by counting the number of selector components for each selector weight category in the selectors that match the element.

  1. ID: This is the count of ID selectors (e.g., #example).
  2. CLASS: This is the count of class selectors (e.g., .my-class), attribute selectors (e.g., [type="radio"]), and pseudo-classes (e.g., :hover).
  3. TYPE: This is the count of type selectors (element names, e.g., h1, div) and pseudo-elements (e.g., ::before).

When comparing selectors to determine which has the highest specificity, look from left to right (ID, then CLASS, then TYPE) and compare the highest value in each column.

It's important to remember that specificity is part of the broader CSS cascade. Declarations marked !important have the highest precedence, followed by inline styles (using the style attribute). Selector specificity comes next.

In cases of equal specificity among competing rules (that aren't inline or !important), the rule that appears last in the CSS source order is the one that counts and will be applied.

References

What's the difference between `block`, `inline`, and `inline-block`?

Topics
CSS
Propertyblockinline-blockinline
SizeFills up the width of its parent container.Depends on content.Depends on content.
PositioningStarts on a new line and tolerates no HTML elements next to it (except when you add float).Flows along with other content and allows other elements beside it.Flows along with other content and allows other elements beside it.
Can specify width and heightYesYesNo. Will be ignored if set.
Can be aligned with vertical-alignNoYesYes
Margins and paddingsAll sides respected.All sides respected.Only horizontal sides respected. Vertical sides, if specified, do not affect layout. Vertical space it takes up depends on line-height, even though the border and padding appear visually around the content.
Float--Becomes like a block element where you can set vertical margins and paddings.
Use casesLayout elements like <div>, <p>, <section>.Used for buttons, images, and form fields that need custom sizes but stay in line with text.Links <a>, text formatting <span>, text styling — bold <b>, italics <i>.

What's the difference between a `relative`, `fixed`, `absolute`, `sticky` and `static`-ally positioned element?

Topics
CSS

A positioned element is an element whose computed position property is either relative, absolute, fixed, or sticky.

  • static: The default position; the element flows into the page as it normally would. The top, right, bottom, left, and z-index properties do not apply.
  • relative: The element's position is adjusted relative to itself, without changing layout (and thus leaving a gap where the element would have been had it not been positioned).
  • absolute: The element is removed from the flow of the page and positioned at a specified position relative to its closest positioned ancestor — or, if none exists, relative to the initial containing block. Absolutely-positioned boxes can have margins, and they do not collapse with any other margins. These elements do not affect the position of other elements.
  • fixed: The element is removed from the flow of the page and positioned at a specified position relative to the viewport, and it doesn't move when scrolled.
  • sticky: Sticky positioning is a hybrid of relative and fixed positioning. The element is treated as relative-positioned until it crosses a specified threshold, at which point it is treated as fixed-positioned.

How do you manipulate CSS styles using JavaScript?

Topics
CSSWeb APIsJavaScript

TL;DR

You can manipulate CSS styles using JavaScript by accessing the style property of an HTML element. For example, to change the background color of a div element with the id myDiv, you can use:

document.getElementById('myDiv').style.backgroundColor = 'blue';

You can also add, remove, or toggle CSS classes using the classList property:

document.getElementById('myDiv').classList.add('newClass');
document.getElementById('myDiv').classList.remove('oldClass');
document.getElementById('myDiv').classList.toggle('toggleClass');

Manipulating CSS styles using JavaScript

Accessing and modifying inline styles

You can directly manipulate the inline styles of an HTML element using the style property. This property allows you to set individual CSS properties.

// Select the element
const myDiv = document.getElementById('myDiv');
// Change the background color
myDiv.style.backgroundColor = 'blue';
// Set multiple styles
myDiv.style.width = '100px';
myDiv.style.height = '100px';
myDiv.style.border = '1px solid black';

Using the classList property

The classList property provides methods to add, remove, and toggle CSS classes on an element. This is useful for applying predefined styles from your CSS files.

// Select the element
const myDiv = document.getElementById('myDiv');
// Add a class
myDiv.classList.add('newClass');
// Remove a class
myDiv.classList.remove('oldClass');
// Toggle a class
myDiv.classList.toggle('toggleClass');

Modifying styles using CSS variables

CSS variables (custom properties) can be manipulated using JavaScript. This is particularly useful for theming and dynamic styling.

// Set a CSS variable
document.documentElement.style.setProperty('--main-color', 'blue');
// Get the value of a CSS variable
const mainColor = getComputedStyle(document.documentElement).getPropertyValue(
'--main-color',
);
console.log(mainColor);

Using external stylesheets

You can also manipulate styles by dynamically adding or removing stylesheets.

// Create a new link element
const link = document.createElement('link');
link.rel = 'stylesheet';
link.href = 'styles.css';
// Append the link element to the head
document.head.appendChild(link);
// Remove the link element
document.head.removeChild(link);

Further reading

Are you familiar with styling SVG?

Topics
CSS

There are several ways to color shapes (including specifying attributes on the object) using inline CSS, an embedded CSS section, or an external CSS file. Most SVGs you find on the web use inline CSS, but there are advantages and disadvantages associated with each type.

Basic coloring can be done by setting two attributes on the node: fill and stroke. fill sets the color inside the object and stroke sets the color of the line drawn around the object. You can use the same CSS color naming schemes that you use in HTML, whether that's color names (e.g. red), RGB values (e.g. rgb(255, 0, 0)), hex values, RGBA values, etc.

<rect
x="10"
y="10"
width="100"
height="100"
stroke="blue"
fill="purple"
fill-opacity="0.5"
stroke-opacity="0.8" />

The above fill="purple" is an example of a presentational attribute. Interestingly, and unlike inline styles like style="fill: purple" which also happens to be an attribute, presentational attributes can be overridden by CSS styles defined in a stylesheet. Hence if you did something like svg { fill: blue; } it will override the purple fill that has been defined.

Can you explain the difference between coding a website to be responsive versus using a mobile-first strategy?

Topics
CSS

These two approaches are not mutually exclusive. Making a website responsive means that some elements will respond by adapting their size or other functionality according to the device's screen size, typically the viewport width, through CSS media queries — for example, making the font size smaller on smaller devices.

@media (min-width: 768px) {
.my-class {
font-size: 24px;
}
}
@media (max-width: 767px) {
.my-class {
font-size: 12px;
}
}

A mobile-first strategy is also responsive; however, it assumes that we should default to and define all the styles for mobile devices, and only add specific responsive rules for other devices later. Following the previous example:

.my-class {
font-size: 12px;
}
@media (min-width: 768px) {
.my-class {
font-size: 24px;
}
}

A mobile-first strategy has the following main advantages:

  • It's more performant on mobile devices, since the rules applied to them don't have to be validated against any media queries.
  • Mobile-first designs are more likely to be usable on larger devices (they will just appear more stretched, but still usable). However, the reverse is not the case.

Can you give an example of an `@media` property other than `screen`?

Topics
CSS

There are four types of @media properties (including screen):

  • all: for all media type devices
  • print: for printers
  • speech: for screen readers that "read" the page out loud
  • screen: for computer screens, tablets, smartphones, etc.

Here is an example of the print media type's usage:

@media print {
body {
color: black;
}
}

Describe `float`s and how they work.

Topics
CSS

Float is a CSS positioning property. Floated elements remain a part of the flow of the page, and will affect the positioning of other elements (e.g. text will flow around floated elements), unlike position: absolute elements, which are removed from the flow of the page.

The CSS clear property can be used to be positioned below left/right/both floated elements.

If a parent element contains nothing but floated elements, its height will be collapsed to nothing. It can be fixed by clearing the float after the floated elements in the container but before the close of the container.

Clearfix hack

The .clearfix hack uses a clever CSS pseudo-element (::after) to clear floats. Rather than setting the overflow on the parent, you apply an additional class clearfix to it. Then apply this CSS:

.clearfix::after {
content: ' ';
visibility: hidden;
display: block;
height: 0;
clear: both;
}

Alternatively, give overflow: auto or overflow: hidden property to the parent element which will establish a new block formatting context inside the children and it will expand to contain its children.

Trivia

In the good old days, CSS frameworks such as Bootstrap 2 used the float property to implement their grid systems. However, with CSS Flexbox and Grid these days, there is no longer much need to use the float property.

References

Describe pseudo-elements and discuss what they are used for.

Topics
CSS

A CSS pseudo-element is a keyword added to a selector that lets you style a specific part of the selected element(s). They can be used for decoration (::first-line, ::first-letter) or for adding elements to the markup (combined with content: ...) without having to modify the markup itself (::before, ::after).

  • ::first-line and ::first-letter can be used to decorate text.
  • Used in the .clearfix hack to add a zero-space element with clear: both.
  • Triangular arrows in tooltips use ::before and ::after. This encourages separation of concerns because the triangle is considered part of styling and not really the DOM.

Notes

  • Pseudo-elements are different from pseudo-classes, which are used to style an element based on its state (such as :hover, :focus, etc.).

References

Describe what you like and dislike about the CSS preprocessors you have used.

Topics
CSS

Likes

Dislikes

  • Sass relies on node-sass, which is a binding for LibSass written in C++. The library has to be recompiled frequently when switching between Node.js versions.
  • In Less, variable names are prefixed with @, which can be confused with native CSS at-rules like @media, @import, and @font-face.

Have you ever used a grid system, and if so, what do you prefer?

Topics
CSS

Before Flex became popular (around 2014), the float-based grid system was the most reliable because it had the most browser support among the alternative existing systems (flex, grid). Bootstrap was using the float approach until Bootstrap 4, which switched to the flex-based approach.

Today, flex is the recommended approach for building grid systems and has excellent browser support.

For the adventurous, look into CSS Grid Layout, which uses the grid property. Grid is a two-dimensional grid-based layout system, compared to Flexbox, which is one-dimensional.

Have you played around with the new CSS Flexbox or Grid specs?

Topics
CSS

Flexbox is mainly meant for one-dimensional layouts, while Grid is meant for two-dimensional layouts.

Flexbox solves many common problems in CSS, such as vertical centering of elements within a container, sticky footers, and so on. Popular CSS frameworks like Bootstrap and Bulma are based on Flexbox, and Flexbox is still the tested and proven way to create a variety of layouts.

Grid is meant for two-dimensional layouts, giving you full control over both rows and columns. It offers an intuitive and powerful way to create complex grid-based designs directly in CSS, often with less code and more flexibility than older techniques. Browser support for Grid is now strong across all major modern browsers, making it a solid option for layout design in most projects.

Have you used or implemented media queries or mobile-specific layouts/CSS?

Topics
CSS

Media queries are a CSS feature that applies styles conditionally based on characteristics of the user's device or viewport, such as width, height, orientation, resolution, or user preferences. They are the foundation of responsive design and let a single CSS file adapt a layout across phones, tablets, and desktops.

Syntax

A media query consists of a media type (e.g. screen, print — see media types) and one or more expressions that evaluate to true or false. When the expressions match, the styles inside the block are applied.

@media (min-width: 768px) {
.card {
display: flex;
}
}
@media (min-width: 768px) and (orientation: landscape) {
.hero {
height: 80vh;
}
}

Common features queried include:

  • min-width / max-width: viewport width thresholds for breakpoints.
  • orientation: portrait or landscape.
  • prefers-color-scheme: light or dark for theming.
  • prefers-reduced-motion: whether the user has requested reduced animations.
  • hover and pointer: whether the primary input has hover capability and how precise it is (e.g. coarse for touch).

Mobile-first vs desktop-first

There are two common approaches to structuring breakpoints:

  • Mobile-first uses min-width queries to layer styles on top of a mobile baseline. This is generally preferred — mobile styles are the default, and larger screens receive progressive enhancements.
  • Desktop-first uses max-width queries to scale a desktop design down. This is easier when retrofitting an existing desktop site but tends to produce more override-heavy CSS.
/* Mobile-first (recommended) */
.nav {
flex-direction: column;
}
@media (min-width: 768px) {
.nav {
flex-direction: row;
}
}

See responsive vs mobile-first for the trade-offs.

Practical example

Transforming a stacked pill navigation into a fixed-bottom tab bar on smaller screens:

.nav {
display: flex;
gap: 8px;
flex-wrap: wrap;
}
@media (max-width: 640px) {
.nav {
position: fixed;
bottom: 0;
left: 0;
right: 0;
justify-content: space-around;
border-top: 1px solid #e5e7eb;
background: #fff;
}
}

Beyond viewport width

Media queries aren't only about screen size. They also let you respect user preferences and device capabilities, which is important for accessibility and UX:

@media (prefers-color-scheme: dark) {
:root {
--bg: #111;
--fg: #eee;
}
}
@media (prefers-reduced-motion: reduce) {
* {
animation-duration: 0.01ms !important;
transition-duration: 0.01ms !important;
}
}
@media (hover: none) and (pointer: coarse) {
.tooltip {
display: none; /* No hover on touch devices */
}
}

Alternatives and newer features

  • Container queries (@container): style a component based on the size of its container rather than the viewport. This is useful for reusable components whose layout should adapt regardless of where they are placed on the page.
  • CSS Flexbox and Grid: often reduce the number of breakpoints needed. flex-wrap, minmax(), and auto-fit/auto-fill can produce fluid layouts that adapt without explicit media queries.
  • Viewport units (vw, vh, svh, dvh): scale sizing with the viewport directly.

References

What are some of the "gotchas" for writing efficient CSS?

Topics
CSS

Firstly, understand that browsers match selectors from rightmost (the key selector) to left. Browsers filter out elements in the DOM according to the key selector, then traverse up their parent elements to determine matches. The shorter the length of the selector chain, the faster the browser can determine if that element matches the selector. Hence, avoid using tag and universal selectors as key selectors — they match a large number of elements, and browsers will have to do more work determining if the parents match.

Be aware of which CSS properties trigger reflow, repaint, and compositing. Avoid writing styles that change the layout (trigger reflow) where possible.

What are the advantages/disadvantages of using CSS preprocessors?

Topics
CSS

Advantages

  • CSS is made more maintainable.
  • Easier to write nested selectors.
  • Variables for consistent theming. Theme files can be shared across different projects. This is now less necessary with CSS custom properties (frequently called CSS variables).
  • Mixins to generate repeated CSS.
  • Sass and Less have features like loops, lists, and maps, which can make configuration easier and less verbose.
  • Splitting your code into multiple files during development. CSS files can be split up too, but doing so will require an HTTP request to download each CSS file.

Disadvantages

  • Requires tools for preprocessing. Recompilation time can be slow.
  • Not writing currently and potentially-usable CSS. For example, by using something like postcss-loader with webpack, you can write potentially future-compatible CSS, allowing you to use things like CSS variables instead of Sass variables. Thus, you're learning new syntax that could pay off if and when it becomes standardized.

What are the different ways to visually hide content (and make it available only for screen readers)?

Topics
AccessibilityCSS

These techniques are related to accessibility (a11y).

Small/zero size

width: 1px; height: 1px combined with CSS clip to make the element take up (barely) any space on the screen at all.

Absolute positioning

position: absolute; left: -99999px will position an element way outside the screen. However, as per WebAIM's article:

Use this only when your content contains only text.

Text indentation

text-indent: -9999px. This only works on text within block elements. Similar to the absolute positioning technique above, focusable elements given this style will still be focusable, causing confusion for sighted users who use keyboard navigation.

Incorrect ways

The following ways are incorrect because they hide content from the user AND screen readers, which is the wrong behavior if the purpose is to expose the content to screen readers only.

  • display: none
  • visibility: hidden
  • hidden attribute

Techniques in the wild

Tailwind CSS

.sr-only {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
white-space: nowrap;
border-width: 0;
}

Bootstrap CSS

.visually-hidden,
.visually-hidden-focusable:not(:focus):not(:focus-within) {
position: absolute !important;
width: 1px !important;
height: 1px !important;
padding: 0 !important;
margin: -1px !important;
overflow: hidden !important;
clip: rect(0, 0, 0, 0) !important;
white-space: nowrap !important;
border: 0 !important;
}

References

What are the various clearing techniques and which is appropriate for what context?

Topics
CSS
  • Empty div method: <div style="clear:both;"></div>.
  • Clearfix method: refer to the .clearfix class.
  • overflow: auto or overflow: hidden method: the parent will establish a new block formatting context and expand to contain its floated children.

What existing CSS frameworks have you used locally, or in production?

How would you change/improve them?
Topics
CSS
  • Bootstrap: Slow release cycle. Bootstrap 4 was in alpha for almost two years. Future versions of Bootstrap should include a spinner button component, as it is widely used.
  • Semantic UI: Source code structure makes theme customization extremely hard to understand. Its unconventional theming system is a pain to customize. Hardcoded config paths within the vendor library. Not well-designed for overriding variables, unlike Bootstrap.
  • Bulma: A lot of non-semantic and superfluous classes and markup required. Not backward-compatible — upgrading versions breaks the app in subtle ways.

Describe Block Formatting Context (BFC) and how it works.

Topics
CSS

A Block Formatting Context (BFC) is part of the visual CSS rendering of a web page in which block boxes are laid out. Floats, absolutely positioned elements, inline-blocks, table-cells, table-captions, and elements with overflow other than visible (except when that value has been propagated to the viewport) establish new block formatting contexts.

A BFC is an HTML box that satisfies at least one of the following conditions:

  • The value of float is not none.
  • The value of position is neither static nor relative.
  • The value of display is table-cell, table-caption, inline-block, flex, inline-flex, grid, or inline-grid.
  • The value of overflow is not visible.

In a BFC, each box's left outer edge touches the left edge of the containing block (for right-to-left formatting, right edges touch).

Vertical margins between adjacent block-level boxes within the same BFC can collapse, but a BFC prevents margin collapsing with elements outside of it. Read more on collapsing margins.

Describe `z-index` and how stacking context is formed.

Topics
CSS

The z-index property in CSS controls the vertical stacking order of elements that overlap. z-index only affects positioned elements (elements which have a position value which is not static) and its descendants or flex items.

Without any z-index value, elements stack in the order that they appear in the DOM (the lowest one down at the same hierarchy level appears on top). Elements with non-static positioning (and their children) will always appear on top of elements with default static positioning, regardless of the HTML hierarchy.

A stacking context is an element that contains a set of layers. Within a local stacking context, the z-index values of its children are set relative to that element rather than to the document root. Layers outside of that context — i.e. sibling elements of a local stacking context — can't sit between layers within it. If an element B sits on top of element A, a child element of element A, element C, can never be higher than element B even if element C has a higher z-index than element B.

Each stacking context is self-contained — after the element's contents are stacked, the whole element is considered in the stacking order of the parent stacking context. A handful of CSS properties trigger a new stacking context, such as opacity less than 1, filter that is not none, and transform that is not none.

Explain CSS sprites, and how you would implement them on a page or site.

Topics
CSSPerformance

CSS sprites combine multiple images into one larger image file and use a combination of CSS background-image, background-position, and background-size to select a specific part of the larger image as the desired image.

It used to be a commonly-used technique for icons (e.g. Gmail uses sprites for all their images).

Advantages

  • Reduces the number of HTTP requests for multiple images (only a single request is required per spritesheet). With HTTP/2, however, loading multiple images is no longer much of an issue.
  • Allows assets to be downloaded in advance before they are needed, such as images that only appear on :hover pseudo-states. No flicker would be seen.

How to implement

  1. Use a sprite generator that packs multiple images into one and generates the appropriate CSS for it.
  2. Each image would have a corresponding CSS class with background-image and background-position properties defined.
  3. To use that image, add the corresponding class to your element.

The generated stylesheet might look something like:

.icon {
background-image: url('https://example.com/images/spritesheet.png');
width: 24px;
height: 24px;
}
.icon-cart {
background-position: 0 0;
}
.icon-arrow {
background-position: -24px 0;
}

And can be used in the HTML as such:

<span class="icon icon-cart"></span>
<span class="icon icon-arrow"></span>

References

Explain how a browser determines what elements match a CSS selector.

Topics
BrowserCSS

This question is related to the question about writing efficient CSS. Browsers match selectors from rightmost (the key selector) to left. Browsers filter out elements in the DOM according to the key selector and traverse up their parent elements to determine matches. The shorter the length of the selector chain, the faster the browser can determine if that element matches the selector.

For example, with a selector p span, browsers first find all the <span> elements and traverse up their parents all the way up to the root to find a <p> element. For a particular <span>, as soon as it finds a <p>, it knows that the <span> matches the selector and can stop traversing its parents.

Have you ever worked with retina graphics?

If so, when and what techniques did you use?
Topics
CSS

Retina is a marketing term used to refer to high-resolution screens with a pixel ratio greater than 1. The key thing to know is that using a pixel ratio means these displays are emulating a lower-resolution screen in order to show elements at the same size. Nowadays, we consider all mobile devices to be retina displays by default.

Browsers render DOM elements according to the device resolution by default, except for images.

To have crisp, good-looking graphics that make the best of retina displays, we need to use high-resolution images whenever possible. However, always using the highest-resolution images will impact performance, as more bytes will need to be sent over the wire.

To overcome this problem, we can use responsive images, as specified in HTML5. This requires making different resolution files of the same image available to the browser and letting it decide which image is best, using the HTML attribute srcset and optionally sizes. For instance:

<div responsive-background-image>
<img
src="/images/test-1600.jpg"
sizes="
(min-width: 768px) 50vw,
(min-width: 1024px) 66vw,
100vw"
srcset="
/images/test-400.jpg 400w,
/images/test-800.jpg 800w,
/images/test-1200.jpg 1200w
" />
</div>

Note that browsers which don't support HTML5's srcset (i.e. IE11) will ignore it and use src instead. If we really need to support IE11 and we want to provide this feature for performance reasons, we can use a JavaScript polyfill, e.g. Picturefill.

For icons, use SVGs where possible, as they render crisply regardless of resolution.

How do you serve your pages for feature-constrained browsers?

What techniques/processes do you use?
Topics
CSS

Techniques

  • Graceful degradation: The practice of building an application for modern browsers while ensuring it remains functional in older browsers.
  • Progressive enhancement: The practice of building an application for a base level of user experience, but adding functional enhancements when a browser supports it.
  • Use caniuse.com to check for feature support.
  • Autoprefixer for automatic vendor prefix insertion.
  • Feature detection using Modernizr.
  • Use CSS feature queries via @supports.

How is responsive design different from adaptive design?

Topics
CSS

Both responsive and adaptive design attempt to optimize the user experience across different devices, adjusting for different viewport sizes, resolutions, usage contexts, control mechanisms, and so on.

Responsive design works on the principle of flexibility — a single fluid website that can look good on any device. Responsive websites use media queries, flexible grids, and responsive images to create a user experience that flexes and changes based on a multitude of factors: like a single ball growing or shrinking to fit through several different hoops.

Adaptive design is more like the modern definition of progressive enhancement. Instead of one flexible design, adaptive design detects the device and other features, and then provides the appropriate features and layout based on a predefined set of viewport sizes and other characteristics. The site detects the type of device used and delivers the pre-set layout for that device. Instead of a single ball going through several different-sized hoops, you'd have several different balls to use depending on the hoop size.

Both of these methods have some issues that need to be weighed:

  • Responsive design can be quite challenging, as you're essentially using a single albeit responsive layout to fit all situations. How to set the media query breakpoints is one such challenge. Do you use standardized breakpoint values? Or, do you use breakpoints that make sense to your particular layout? What if that layout changes?
  • Adaptive design generally requires user agent sniffing, or DPI detection, etc., all of which can prove unreliable.

How would you approach fixing browser-specific styling issues?

Topics
CSS
  • After identifying the issue and the offending browser, use a separate stylesheet that only loads when that specific browser is being used. This technique requires server-side rendering, though.
  • Use libraries like Bootstrap that already handle these styling issues for you.
  • Use autoprefixer to automatically add vendor prefixes to your code.
  • Use Reset CSS or Normalize.css.
  • If you're using PostCSS (or a similar CSS transpilation library), there may be plugins that allow you to opt in to using modern CSS syntax (and even W3C proposals) which will transform those sections of your code into equivalent backward-compatible code that will work in the targets you've specified.

Is there any reason you'd want to use `translate()` instead of `absolute` positioning, or vice-versa? And why?

Topics
CSSPerformance

translate() is a possible value of the CSS transform property. When using translate(), the element still occupies its original space (sort of like position: relative). But when changing the absolute positioning of an element, the element is removed from the flow of the page and the positioning of surrounding elements will be affected. Hence, the page layout will have to be recalculated.

Changing transform or opacity does not trigger browser reflows or repaints — only compositing. On the other hand, changing absolute positioning triggers a reflow. transform causes the browser to create a GPU layer for the element, but changing absolute positioning properties uses the CPU. Hence, translate() is more efficient and will result in shorter paint times for smoother animations.

What's the difference between "resetting" and "normalizing" CSS?

Which would you choose, and why?
Topics
CSS
TermDefinition
ResettingResetting is meant to strip all default browser styling from elements. For example, margins, paddings, and font-sizes of all elements are reset to be the same. You will have to redeclare styling for common typographic elements.
NormalizingNormalizing preserves useful default styles rather than "unstyling" everything. It also corrects bugs for common browser dependencies.

Which to choose and why?

Choose resetting when you need to have a very customized or unconventional site design such that you need to do a lot of your own styling and do not need any default styling to be preserved.

Explain your understanding of the box model and how you would tell the browser in CSS to render your layout in different box models.