A comprehensive, interview-focused CSS reference covering fundamentals through advanced concepts, layout systems, responsive design, performance, methodologies, preprocessors, and modern CSS tools.
This guide is organized into 11 core sections, progressing from CSS fundamentals to advanced architecture and tooling:
- 1. CSS Basics & Syntax
- 2. CSS Selectors & Specificity
- 3. The Box Model & Sizing
- 4. Positioning & Display Properties
- 5. CSS Units & Formatting
- 6. Layouts: Flexbox & CSS Grid
- 7. Responsive Web Design & Media Queries
- 8. Transitions, Transforms & Animations
- 9. Advanced CSS Concepts & Performance
- 10. CSS Methodologies & Preprocessors
- 11. Modern CSS Frameworks & Tools
- Read each question and try to answer it before revealing the explanation.
- Pay special attention to the code examples and understand why each property behaves as shown.
- Use the guide for revision before CSS interviews and technical discussions.
- Practice explaining concepts in your own words rather than memorizing definitions.
- For advanced topics, combine the theory with small hands-on examples.
It covers everything from basic syntax to advanced layout techniques, performance optimization, and modern CSS methodologies.
CSS stands for Cascading Style Sheets. It is used to separate web page content (HTML) from its visual presentation (design, layout, and variations for different devices and screen sizes).
Key Concepts:
- Selectors: Elements to which the style rules apply.
- Properties: Visual features, such as
font-size,color, andbackground. - Values: Specific settings for properties, like
redfor the color property.
The "cascading" refers to the hierarchy of styles applied to an element. Styles cascade down from multiple sources:
- Browser Default Styles: Built-in user agent stylesheets.
- User Styles: Custom styles set by the user in their browser.
- Author Styles: Styles written by the web developer. If there are conflicts, CSS uses Specificity and Source Order to determine which rule wins. Author styles override browser styles, and later rules override earlier ones (if specificity is equal).
There are three primary methods:
- Inline CSS: Directly inserted into an HTML tag using the
styleattribute.- Best for: Quick fixes or dynamic styles applied via JS.
- Example:
<p style="color: red;">Hello</p>
- Internal (Embedded) CSS: Placed inside a
<style>tag within the HTML document's<head>.- Best for: Single-page styles that shouldn't be cached separately.
- External CSS: A standalone
.cssfile linked via the<link>tag.- Best for: Maintainability, caching, and multi-page websites. (Recommended)
At-rules are CSS statements that instruct CSS how to behave. They begin with an @ sign.
@import: Imports another stylesheet.@media: Applies styles based on device conditions (responsive design).@keyframes: Defines CSS animation steps.@font-face: Allows custom fonts to be loaded.@supports: Feature queries to check if a browser supports a property.
CSS3 introduced a wealth of new capabilities:
- Selectors:
:not(),:nth-child(), attribute matching^=,$=,*=. - Visual Effects:
border-radius,box-shadow,text-shadow. - Gradients:
linear-gradient(),radial-gradient(),conic-gradient(). - Colors:
rgba(),hsla()with alpha transparency. - Layouts: Flexbox and CSS Grid.
- Transitions & Animations: Smooth state changes without JavaScript.
- Transforms: 2D and 3D manipulation (
rotate,scale,translate).
- Class Selector (
.classname): Can be applied to multiple HTML elements. An element can also have multiple classes. - ID Selector (
#idName): Must be unique to a single HTML element on a page. - Performance: Modern browsers handle both efficiently, though ID technically has higher specificity.
- Best Practice: Use classes for styling and IDs for JavaScript hooks or in-page anchor links.
:nth-child(n)looks at the element's position among all its siblings, regardless of type.:nth-of-type(n)looks at the element's position only among siblings of the same element type.
Example:
<div>
<p>Paragraph 1</p> <!-- p:nth-child(1), p:nth-of-type(1) -->
<span>Span 1</span> <!-- span:nth-child(2), span:nth-of-type(1) -->
<p>Paragraph 2</p> <!-- p:nth-child(3), p:nth-of-type(2) -->
</div>Combinators define the relationship between selectors.
- Descendant (space):
div p- Selects all<p>inside<div>(any level deep). - Child (
>):div > p- Selects<p>that are direct children of<div>. - Adjacent Sibling (
+):div + p- Selects the first<p>immediately after a<div>. - General Sibling (
~):div ~ p- Selects all<p>elements that follow a<div>.
Specificity determines which CSS rule is applied when multiple rules target the same element. It is calculated as a 4-part value: (Inline, ID, Class/Pseudo/Attr, Element/Pseudo-element).
- Inline styles:
1,0,0,0(Highest) - IDs:
0,1,0,0 - Classes, attributes, pseudo-classes:
0,0,1,0 - Elements, pseudo-elements:
0,0,0,1
Note: !important overrides all specificity, but should be avoided when possible.
- Pseudo-classes (
:): Selects elements based on their state or position (e.g.,:hover,:focus,:first-child,:checked). - Pseudo-elements (
::): Creates or selects a specific part of an element (e.g.,::before,::after,::first-letter).
The * selector targets every single element on the page. It is commonly used in CSS resets to remove default margins and paddings.
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}The Box Model describes how every HTML element is wrapped in a rectangular box consisting of four areas:
- Content: The actual text, image, or media.
- Padding: Transparent space inside the border, pushing content away from edges.
- Border: A visible (or invisible) line surrounding the padding.
- Margin: Transparent space outside the border, separating this box from others.
By default, box-sizing: content-box means width and height only apply to the content. Adding padding or borders expands the total size of the box.
Setting box-sizing: border-box forces the width and height to include the padding and border. This makes layout calculations vastly easier.
/* The gold standard reset */
*, *::before, *::after {
box-sizing: border-box;
}- Padding is inside the element. It affects the element's total size (unless
border-boxis used) and pushes content away from the border. Background colors apply to padding. - Margin is outside the element. It creates space between adjacent elements. Background colors do not apply to margins.
Vertical margins (top and bottom) of adjacent block elements sometimes collapse into a single margin equal to the largest of the two, rather than stacking together.
- Horizontal margins never collapse.
- How to prevent it: Add
padding,border, oroverflow: hiddento the parent, or use Flexbox/Grid layouts (which do not collapse margins).
width: auto(default): The element fills the container but will shrink to accommodate padding and borders without overflowing.width: 100%: Forces the element's content to be 100% of the parent's width. Any padding or borders are added to this, causing the element to overflow its container (unlessbox-sizing: border-boxis applied).
- Block (
display: block): Starts on a new line, takes up the full width available. Respects width, height, margin, and padding on all sides. (e.g.,<div>,<p>). - Inline (
display: inline): Does not start on a new line, takes up only necessary width. Ignoreswidth,height, and top/bottom margins/padding. (e.g.,<span>,<a>). - Inline-Block (
display: inline-block): Flows like an inline element but respectswidth,height, and all margins/padding. (e.g.,<button>,<input>).
What is the difference between display: none and visibility: hidden?
display: none: Removes the element from the document flow entirely. It takes up zero space and cannot be interacted with.visibility: hidden: Hides the element, but it still takes up its original space in the layout.
static(Default): Elements flow normally in the document.top,left,z-indexhave no effect.relative: Positioned relative to its normal position. Settingtop: 10pxmoves it 10px down from where it normally sits. It still occupies its original space.absolute: Removed from the normal flow. Positioned relative to its closest positioned ancestor (an ancestor that is notstatic). If none exists, it positions relative to the document body.fixed: Positioned relative to the browser viewport. It stays in the exact same place even when the page is scrolled.sticky: A hybrid of relative and fixed. It acts relative until it hits a defined threshold (e.g.,top: 0), then acts fixed.
z-index controls the vertical stacking order of overlapping positioned elements (elements with position other than static). Higher values appear on top.
A Stacking Context is formed by:
- The root element (
<html>) - Positioned elements with a
z-indexvalue - Elements with
opacity< 1 - Elements with
transform,filter, orwill-changeproperties. Once a stacking context is formed, thez-indexof its children only applies within that context.
float pushes an element to the left or right of its container, allowing text and inline elements to wrap around it. However, floated elements are removed from normal flow, causing parent containers to collapse (height becomes 0).
Clearing Floats (Clearfix):
/* Modern Clearfix */
.container::after {
content: "";
display: table;
clear: both;
}Note: Today, Flexbox and Grid have largely replaced the need for floats in layout design.
- Absolute:
px(pixels),pt(points),cm,mm,in. - Font-Relative:
em(relative to parent font-size),rem(relative to root<html>font-size),ch(width of '0' character). - Viewport-Relative:
vw(1% of viewport width),vh(1% of viewport height),vmin,vmax.
em: Relative to the font-size of its direct parent. Compounds when nested (1.2em inside 1.2em becomes 1.44em).rem: Relative to the root<html>element. Always consistent regardless of where it is placed in the DOM. (Preferred for consistency).
calc() allows mathematical operations in CSS values, enabling the mixing of different units.
.sidebar {
width: calc(100% - 250px); /* Full width minus 250px */
padding: calc(1vw + 1em);
}- Font:
font-family,font-size,font-weight,font-style,font-variant. - Text:
color,text-align,text-decoration,text-transform,text-indent,letter-spacing,word-spacing,line-height,word-wrap.
CSS counters are variables maintained by CSS whose values can be incremented and used to style content based on their position in the document.
body {
counter-reset: section;
}
h3::before {
counter-increment: section;
content: "Section " counter(section) ": ";
}Flexbox (Flexible Box Layout) is a one-dimensional layout model designed for laying out items in rows or columns. It excels at distributing space dynamically and aligning items.
Key Container Properties:
display: flex;flex-direction:row,columnjustify-content: Aligns items horizontally (main axis).center,space-between,space-around.align-items: Aligns items vertically (cross axis).center,stretch,flex-start.flex-wrap:wrap,nowrap.
Key Item Properties:
flex-grow: How much an item should grow to fill space.flex-shrink: How much it should shrink.flex-basis: Initial size before growing/shrinking.align-self: Overridesalign-itemsfor one item.
CSS Grid is a two-dimensional layout system, allowing you to handle both rows and columns simultaneously. It is ideal for complex page layouts.
Key Properties:
display: grid;grid-template-columns: Defines column sizes (e.g.,1fr 1fr 2frorrepeat(3, 1fr)).grid-template-rows: Defines row sizes.gap: (orgrid-gap) Space between rows and columns.grid-area: Assigns a grid item to a named area.
- Use Flexbox for 1D layouts (navigation bars, aligning items within a component, menu items). It is content-first.
- Use CSS Grid for 2D layouts (overall page structure, complex photo galleries). It is layout-first.
Method 1: Flexbox (Easiest)
.parent {
display: flex;
justify-content: center; /* Horizontal */
align-items: center; /* Vertical */
}Method 2: Auto Margins (Block elements)
.child {
width: 200px;
margin: 0 auto; /* Centers horizontally */
}Method 3: CSS Grid
.parent {
display: grid;
place-items: center;
}RWD is an approach ensuring web pages render well on a variety of devices and window/screen sizes. Its foundations are:
- Fluid Grids (using relative units like
%orfr). - Flexible Media (images using
max-width: 100%). - Media Queries.
- Responsive: One fluid layout that smoothly adapts to any screen size. The layout "responds" continuously.
- Adaptive: Several distinct layouts designed for specific screen sizes (e.g., mobile, tablet, desktop). The server or browser detects the device and serves the appropriate layout.
A media query is a CSS block that only applies styles if a specific condition is true.
@media (min-width: 768px) {
body {
background-color: lightblue;
}
}- Mobile-First: Default CSS targets mobile devices. Media queries use
min-widthto add complexity as the screen gets larger. (Highly recommended for performance). - Desktop-First: Default CSS targets desktops. Media queries use
max-widthto simplify layouts as the screen gets smaller.
/* Mobile-First Approach */
.col { width: 100%; }
@media (min-width: 768px) {
.col { width: 50%; } /* Apply to tablets and up */
}Retina (or high-DPI) screens have more physical pixels per inch, requiring higher-resolution images to appear sharp. Techniques:
- Use
srcsetattribute in HTML to serve different image files based on device pixel ratio (DPR). - Use Vector graphics (SVGs) for icons and logos.
- Use CSS media queries targeting
-webkit-min-device-pixel-ratio: 2.
CSS sprites combine multiple small images (like icons) into one larger image file. You then use background-position to display only the desired part.
- Benefit: Reduces the number of HTTP requests, improving load time. (Note: With HTTP/2, this is less critical, and SVGs/Icon fonts are often preferred).
Transitions allow property changes in CSS values to occur smoothly over a specified duration, rather than instantly.
.button {
background-color: blue;
transition: background-color 0.3s ease;
}
.button:hover {
background-color: darkblue;
}Properties: transition-property, transition-duration, transition-timing-function (e.g., ease, linear), transition-delay.
Transforms allow you to visually manipulate an element without affecting the normal document flow.
- 2D:
translate(),rotate(),scale(),skew(). - 3D:
rotateX(),rotateY(),perspective().
.card:hover {
transform: translateY(-10px) scale(1.05);
}Yes. transform: translate() is hardware-accelerated (uses the GPU) and does not trigger DOM reflow or repaint, making animations significantly smoother. absolute positioning uses the CPU and triggers reflow, which can cause jitter.
Animations allow complex, multi-step movements using @keyframes.
@keyframes slideIn {
from { transform: translateX(-100%); opacity: 0; }
to { transform: translateX(0); opacity: 1; }
}
.modal {
animation: slideIn 0.5s ease-out forwards;
}Tweening (in-betweening) is the process of generating intermediate frames between two states to create the illusion of smooth motion. CSS handles tweening automatically when you use transition or animation properties.
A BFC is a self-contained rendering area in CSS. Elements inside a BFC are laid out independently of elements outside.
- What creates a BFC?
float(not none),position(absolute/fixed),display(flex, grid, inline-block),overflow(hidden, auto). - Practical Use: Preventing margin collapsing between parent/child, and containing floated elements (clearfix alternative).
- Reflow: Occurs when the browser must recalculate the position and geometry of elements (e.g., changing
width,margin,display). It is highly performance-intensive. - Repaint: Occurs when visual aspects change without affecting layout (e.g.,
color,background-color). Less intensive than reflow. - Optimization: Use
transformandopacityfor animations to trigger only compositor operations, avoiding reflow/repaint.
Techniques to render content as quickly as possible rather than waiting for the entire page to load.
- Lazy loading images.
- Prioritizing above-the-fold content (critical CSS).
- Async HTML fragments.
- CSS Resets/Normalize.css: Establish a consistent baseline.
- Vendor Prefixes: Use Autoprefixer for properties requiring
-webkit-,-moz-, etc. - Feature Queries: Use
@supportsto check if a browser supports a property before applying it. - Graceful Degradation / Progressive Enhancement: Build for modern browsers but ensure basic functionality remains for older ones.
Extensions to CSS standards added by browser vendors to support experimental features before standardization.
-webkit-(Chrome, Safari, Edge)-moz-(Firefox)-ms-(Internet Explorer)-o-(Old Opera)
The filter property applies graphical effects like blur, color shift, or brightness.
img:hover {
filter: grayscale(100%) blur(2px);
}Variables defined by the developer that can be reused throughout the document. They are evaluated at runtime (unlike preprocessor variables).
:root {
--primary-color: #3498db;
}
.button {
background-color: var(--primary-color);
}Ensuring content is usable by people with disabilities.
- Visually hiding content for screen readers: Use specific CSS to hide text visually but keep it readable by screen readers.
.visually-hidden {
position: absolute;
width: 1px; height: 1px;
overflow: hidden;
clip: rect(0 0 0 0);
}A scripting language that extends CSS with features like variables, nesting, mixins, and functions, then compiles it into standard CSS.
- Popular options: SASS/SCSS, LESS, Stylus.
SASS (Syntactically Awesome Style Sheets) is a preprocessor.
- SASS: Uses strict indentation and no curly braces or semicolons.
- SCSS: Uses standard CSS syntax (curly braces and semicolons) but adds SASS features. (SCSS is the most widely used).
Mixins are reusable blocks of CSS code that can accept arguments.
@mixin border-radius($radius) {
-webkit-border-radius: $radius;
-moz-border-radius: $radius;
border-radius: $radius;
}
.box { @include border-radius(10px); }A naming convention for CSS classes to make them modular and maintainable.
- Block: Standalone entity (
.button) - Element: Part of a block (
.button__icon) - Modifier: Variation of a block/element (
.button--large,.button--disabled)
Object-Oriented CSS. A methodology focused on two principles:
- Separate Structure from Skin (layout vs. visual styling).
- Separate Container from Content (elements should look the same regardless of where they are placed).
Scalable and Modular Architecture for CSS. A style guide that categorizes CSS rules into 5 types: Base, Layout, Module, State, and Theme.
- CSS Reset: Strips ALL default browser styling. You start from a blank slate and must style everything yourself.
- Normalize.css: Retains useful default browser styles but corrects inconsistencies across browsers. (Generally preferred).
Tailwind is a utility-first CSS framework. Instead of providing pre-built components (like Bootstrap), it provides low-level utility classes (e.g., mt-4, text-center, flex) that you combine to build custom designs directly in your HTML.
- Pros: Rapid prototyping, built-in cross-browser compatibility, established components.
- Cons: Bloated code (unused CSS), generic "Bootstrap look", overriding default styles can be tedious.
A tool (like Stylelint) that checks your CSS code for syntax errors, bad practices, and enforces consistent formatting rules.
A tool used to remove unused CSS from your final production files. It scans your HTML/JS files and deletes any CSS classes that are not actively being used. Essential for utility frameworks like Tailwind to keep file sizes small.