CSS Interview Questions (Free Preview)
Free sample of 14 from 54 questions available
Basic Concepts
What does the CSS box model represent?
The CSS box model is a fundamental concept that describes how elements are structured and how their dimensions are calculated. It consists of four concentric rectangular areas:
- Content: The innermost area containing text, images, or other elements
- Padding: Space between content and border (transparent)
- Border: A line surrounding the padding and content
- Margin: The outermost space between the element and adjacent elements
The box model determines:
- How element dimensions are calculated
- How spacing affects layout
- How elements interact with each other spatially
Two box-sizing models exist:
content-box(default): Width/height applies only to contentborder-box: Width/height includes padding and border
References:
↑ Back to topCan you explain the differences between margin and padding?
Margin and padding are both spacing properties but serve different purposes within the CSS box model:
Margin:
- Space outside the element's border
- Creates distance between elements
- Transparent and does not have a background color
- Can have negative values
- Experiences margin collapse in certain situations
- Not included in the element's clickable area
Padding:
- Space inside the element's border, between content and border
- Creates internal spacing within the element
- Takes on the element's background color/image
- Cannot have negative values
- Increases the element's clickable area
- Affects the element's total size when
box-sizing: content-box
References:
↑ Back to topSelectors and Specificity
How does the cascade and specificity work in CSS?
The CSS cascade determines which styles are applied when multiple rules target the same element. The cascade follows this order of importance:
1. Origin and Importance
- User agent styles (browser defaults)
- User styles
- Author styles (your CSS)
!importantdeclarations reverse this order
2. Specificity Calculated using a four-part value (a, b, c, d):
a: Inline styles (1000 points)b: ID selectors (100 points each)c: Class selectors, attribute selectors, pseudo-classes (10 points each)d: Type selectors and pseudo-elements (1 point each)
3. Source Order
- When specificity is equal, the last rule in source order wins
Example:
/* Specificity: 0,0,1,1 (11 points) */
p.intro { color: blue; }
/* Specificity: 0,1,0,1 (101 points) - wins */
#content p { color: red; }
/* Specificity: 1,0,0,0 (1000 points) - wins */
<p style="color: green;">
Reference: MDN Web Docs - Specificity
↑ Back to topWhat are pseudo-classes and pseudo-elements? Give examples of each.
Pseudo-classes select elements based on their state or position in the document tree:
State-based pseudo-classes:
a:hover { color: red; }
input:focus { border: 2px solid blue; }
button:disabled { opacity: 0.5; }
Structural pseudo-classes:
li:first-child { font-weight: bold; }
tr:nth-child(even) { background-color: #f2f2f2; }
p:last-of-type { margin-bottom: 0; }
Pseudo-elements create virtual elements or select parts of elements:
/* Insert content before/after elements */
h1::before { content: "★ "; }
p::after { content: " [End]"; }
/* Style specific parts of text */
p::first-line { font-weight: bold; }
p::first-letter { font-size: 2em; }
/* Style form placeholders */
input::placeholder { color: #999; }
Key difference: Pseudo-classes use single colon (:) while pseudo-elements use double colon (::) in modern CSS.
Reference: MDN Web Docs - Pseudo-classes | MDN Web Docs - Pseudo-elements
↑ Back to topLayout and Positioning
What are the different methods of positioning elements (static, relative, absolute, fixed, sticky)?
CSS positioning controls how elements are placed within the document flow:
- Static: Default positioning. Elements follow normal document flow and are not affected by top, right, bottom, left properties.
- Relative: Element is positioned relative to its normal position. Creates a new stacking context and serves as a reference point for absolutely positioned children.
- Absolute: Element is removed from document flow and positioned relative to its nearest positioned ancestor (or viewport if none exists).
- Fixed: Element is positioned relative to the viewport and remains in the same position during scrolling.
- Sticky: Element switches between relative and fixed positioning based on scroll position. It's relative until it reaches a specified threshold, then becomes fixed.
References:
↑ Back to topWhat are the main concepts and properties of Flexbox?
Main concepts:
- Flex Container: Parent element with
display: flex - Flex Items: Direct children of flex container
- Main Axis: Primary direction of flex container
- Cross Axis: Perpendicular to main axis
Key properties:
/* Container properties */
.flex-container {
display: flex;
flex-direction: row | column;
flex-wrap: nowrap | wrap;
justify-content: flex-start | center | space-between | space-around;
align-items: stretch | center | flex-start | flex-end;
align-content: stretch | center | space-between;
gap: 10px;
}
/* Item properties */
.flex-item {
flex: 1; /* shorthand for flex-grow, flex-shrink, flex-basis */
flex-grow: 0;
flex-shrink: 1;
flex-basis: auto;
align-self: auto | center | flex-start | flex-end;
order: 0;
}
References:
↑ Back to topHow does CSS Grid differ from Flexbox, and in which use cases are they each more appropriate?
Key differences:
| Aspect | Flexbox | CSS Grid |
|---|---|---|
| Dimension | One-dimensional (row OR column) | Two-dimensional (rows AND columns) |
| Layout approach | Content-first | Layout-first |
| Alignment | Along main/cross axis | In both dimensions simultaneously |
| Item sizing | Flexible, content-based | Fixed/flexible with explicit control |
Use cases:
Flexbox is better for:
- Navigation bars
- Button groups
- Centering content
- Distributing space among items
- One-dimensional layouts
/* Flexbox example - navigation */
.nav {
display: flex;
justify-content: space-between;
align-items: center;
}
CSS Grid is better for:
- Page layouts
- Complex two-dimensional layouts
- Overlapping elements
- Precise positioning requirements
/* Grid example - page layout */
.page-layout {
display: grid;
grid-template-areas:
"header header header"
"sidebar main aside"
"footer footer footer";
grid-template-columns: 200px 1fr 150px;
grid-template-rows: auto 1fr auto;
}
References:
- CSS-Tricks - CSS Grid vs Flexbox
- MDN Web Docs - CSS Grid Layout
- Rachel Andrew - Should I use Grid or Flexbox?
How do you center an element horizontally and vertically using modern approaches (e.g., Flexbox, CSS Grid)?
Flexbox approach:
.flex-container {
display: flex;
justify-content: center; /* horizontal */
align-items: center; /* vertical */
height: 100vh;
}
CSS Grid approach:
.grid-container {
display: grid;
place-items: center; /* both directions */
height: 100vh;
}
/* Alternative Grid syntax */
.grid-container-alt {
display: grid;
justify-content: center;
align-content: center;
height: 100vh;
}
Transform approach:
.transform-center {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
References:
↑ Back to topResponsive Design Interview Questions
What are media queries and how are they used to create responsive designs?
Media queries are CSS features that allow you to apply different styles based on device characteristics such as screen width, height, orientation, and resolution. They are the foundation of responsive web design, enabling websites to adapt their layout and appearance across different devices.
Basic syntax:
@media screen and (max-width: 768px) {
.container {
width: 100%;
padding: 10px;
}
}
Common breakpoints:
- Mobile:
max-width: 767px - Tablet:
min-width: 768pxandmax-width: 1023px - Desktop:
min-width: 1024px
Media queries can target various properties including:
- Width and height (
min-width,max-width) - Device orientation (
orientation: portraitorlandscape) - Resolution (
min-resolution,max-resolution) - Display type (
screen,print)
References:
↑ Back to topWhat does mobile-first design mean, and why might you choose it?
Mobile-first design is a development approach where you design and code for mobile devices first, then progressively enhance the experience for larger screens using media queries.
Implementation approach:
/* Base styles for mobile */
.container {
width: 100%;
padding: 15px;
}
/* Tablet styles */
@media screen and (min-width: 768px) {
.container {
max-width: 750px;
margin: 0 auto;
}
}
/* Desktop styles */
@media screen and (min-width: 1024px) {
.container {
max-width: 1200px;
padding: 30px;
}
}
Benefits of mobile-first:
- Performance: Smaller CSS files load faster on mobile devices
- Progressive enhancement: Builds upon a solid foundation
- Focus on content: Forces prioritization of essential content
- Better user experience: Ensures core functionality works on all devices
- Future-proof: Accommodates the mobile-dominant web landscape
- SEO advantages: Google's mobile-first indexing prioritizes mobile-optimized sites
References:
↑ Back to topAdvanced Topics and Custom Properties
What are CSS Custom Properties (variables) and how do they differ from preprocessor variables?
CSS Custom Properties (CSS variables) are native CSS features that allow developers to store and reuse values throughout a stylesheet. They are defined using the -- prefix and accessed using the var() function.
Key characteristics of CSS Custom Properties:
- Runtime evaluation: Values are calculated and can be changed at runtime using JavaScript
- Cascading and inheritance: They follow CSS cascade rules and can inherit values from parent elements
- Scoping: Can be scoped to specific elements or globally using
:root - Dynamic: Can be modified via JavaScript and media queries
:root {
--primary-color: #3498db;
--font-size: 16px;
}
.element {
color: var(--primary-color);
font-size: var(--font-size, 14px); /* fallback value */
}
Differences from preprocessor variables (Sass, Less, Stylus):
| Feature | CSS Custom Properties | Preprocessor Variables |
|---|---|---|
| Evaluation time | Runtime | Compile time |
| JavaScript access | Yes | No |
| Cascading | Yes | No |
| Media query responsive | Yes | No |
| Browser support | Modern browsers | All (compiled to CSS) |
| Scope | CSS cascade rules | Lexical scope |
References:
↑ Back to topAdvanced Selectors and Techniques
How do CSS animations differ from transitions?
CSS animations and transitions both create smooth changes in CSS properties, but they serve different purposes and have different capabilities.
Key Differences:
| Feature | Transitions | Animations |
|---|---|---|
| Trigger | Requires user interaction or state change | Can run automatically |
| Control | Only start and end states | Multiple keyframes |
| Direction | Bidirectional | Can be unidirectional or bidirectional |
| Repetition | Runs once per trigger | Can loop infinitely |
| Timing | Single timing function | Different timing for each keyframe |
CSS Transitions:
/* Simple transition example */
.button {
background-color: blue;
padding: 10px 20px;
transition: background-color 0.3s ease, padding 0.3s ease;
}
.button:hover {
background-color: red;
padding: 15px 25px;
}
/* Transition with delay */
.delayed-transition {
opacity: 1;
transition: opacity 0.5s ease 0.2s; /* delay of 0.2s */
}
.delayed-transition:hover {
opacity: 0.5;
}
CSS Animations:
/* Define keyframes */
@keyframes slideIn {
0% {
transform: translateX(-100%);
opacity: 0;
}
50% {
opacity: 0.5;
}
100% {
transform: translateX(0);
opacity: 1;
}
}
/* Apply animation */
.animated-element {
animation: slideIn 2s ease-in-out;
}
/* Complex animation with multiple properties */
@keyframes pulse {
0%, 100% {
transform: scale(1);
background-color: blue;
}
50% {
transform: scale(1.1);
background-color: red;
}
}
.pulsing-element {
animation: pulse 2s infinite alternate;
}
/* Animation shorthand properties */
.comprehensive-animation {
animation:
slideIn 2s ease-in-out 0.5s infinite alternate both running;
/*
animation-name: slideIn;
animation-duration: 2s;
animation-timing-function: ease-in-out;
animation-delay: 0.5s;
animation-iteration-count: infinite;
animation-direction: alternate;
animation-fill-mode: both;
animation-play-state: running;
*/
}
When to Use Each:
Use Transitions for:
- Hover effects
- Form interactions
- Simple state changes
- UI feedback
Use Animations for:
- Loading spinners
- Attention-grabbing effects
- Complex multi-step animations
- Automatic/continuous animations
/* Practical example: Loading spinner */
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
.spinner {
width: 40px;
height: 40px;
border: 4px solid #f3f3f3;
border-top: 4px solid #3498db;
border-radius: 50%;
animation: spin 1s linear infinite;
}
References:
↑ Back to topPreprocessors, Methodologies, and Architecture
Can you explain BEM (Block Element Modifier) naming convention and why it's useful?
BEM (Block Element Modifier) is a CSS naming methodology that provides a structured approach to naming CSS classes. It was developed by Yandex to create scalable and maintainable CSS.
BEM Structure:
- Block: A standalone component (e.g.,
header,menu,button) - Element: A part of a block that has no standalone meaning (e.g.,
header__title,menu__item) - Modifier: A flag that changes appearance or behavior (e.g.,
button--primary,menu--vertical)
Naming Convention:
.block {}
.block__element {}
.block--modifier {}
.block__element--modifier {}
Example:
/* Block */
.card {}
/* Elements */
.card__header {}
.card__body {}
.card__footer {}
/* Modifiers */
.card--featured {}
.card__header--large {}
Benefits:
- Modularity: Each block is independent and reusable
- Clarity: Class names clearly indicate structure and purpose
- Maintainability: Easy to understand and modify code
- Scalability: Consistent naming prevents conflicts in large projects
- Searchability: Easy to find related styles in codebase
References:
↑ Back to topPerformance and Optimization
What are critical CSS and how do you implement it?
Critical CSS refers to the minimum CSS required to render above-the-fold content, typically the first screen users see when loading a page.
Implementation Strategies:
Manual Extraction:
- Identify above-the-fold elements and their required styles
- Create a separate critical CSS file with only essential styles
- Inline critical CSS in the HTML
<head>section
Automated Tools:
- Use tools like Critical, Penthouse, or Puppeteer-based solutions
- Integrate critical CSS extraction into build processes
- Implement dynamic critical CSS generation for different viewport sizes
Best Practices:
- Keep critical CSS under 14KB (TCP slow start limit)
- Include reset/normalize styles in critical CSS
- Cover typography, layout, and basic styling for key elements
- Load remaining CSS asynchronously after page load
Implementation Example:
<!DOCTYPE html>
<html>
<head>
<style>
/* Critical CSS inlined here */
body { font-family: Arial, sans-serif; margin: 0; }
.header { background: #333; color: white; padding: 1rem; }
.hero { height: 100vh; background: linear-gradient(...); }
</style>
<!-- Non-critical CSS loaded asynchronously -->
<link rel="preload" href="styles.css" as="style" onload="this.onload=null;this.rel='stylesheet'">
<noscript><link rel="stylesheet" href="styles.css"></noscript>
</head>
</html>
References:
↑ Back to top