CSS Basics
1. What does CSS stand for and what is its purpose?
CSS stands for Cascading Style Sheets. It is a stylesheet language used to style and layout web pages โ controlling colors, fonts, spacing, positioning, and visual effects.
Key purposes:
- Add colors, fonts, and visual styling to HTML content
- Control layout and spacing (padding, margins, positioning)
- Create responsive designs that work on different screen sizes
- Enable animations and transitions
- Separate presentation from content
CSS works alongside HTML (structure) and JavaScript (interactivity) to create complete web pages.
2. Explain the CSS box model.
The CSS box model describes how elements are structured in terms of content, padding, border, and margin.
From inside out:
- Content: The actual content (text, images) inside the element
- Padding: Space inside the element, between content and border
- Border: Line around the padding
- Margin: Space outside the element, between the element and other elements
Total width calculation (by default):
Total Width = Content Width + Padding + Border + Margin
To simplify: Use box-sizing: border-box; to include padding and border in the width calculation.
3. What is CSS specificity and how does it work?
CSS specificity determines which style rules apply when multiple rules target the same element. It's a priority system for styles.
Specificity hierarchy (lowest to highest):
- Element selectors:
p { }โ 1 point - Class selectors:
.class { }โ 10 points - ID selectors:
#id { }โ 100 points - Inline styles:
style="color:red;"โ 1000 points !importantโ Highest priority (use sparingly)
Example: #header .nav ul li.active a { } = 100 + 10 + 1 + 1 + 10 + 1 = 123 points
Best practice: Keep specificity low for maintainability. Avoid !important.
4. What is the cascade in CSS and how does it work?
The "cascade" in Cascading Style Sheets refers to how CSS rules are applied when multiple rules apply to the same element.
Order of precedence:
- Browser default styles (lowest priority)
- External stylesheets
- Internal stylesheets (in
<style>tag) - Inline styles (highest priority)
If specificity is equal: The last rule written wins.
Example: If you have two rules with equal specificity, the one that appears later in the code takes precedence.
Understanding the cascade is crucial for writing maintainable CSS and avoiding conflicts.
5. What are CSS pseudo-classes and pseudo-elements?
Pseudo-classes: Define a special state of an element.
Syntax: selector:pseudo-class
Common pseudo-classes:
:hoverโ When user hovers over element:activeโ When element is being clicked:focusโ When element has focus:visitedโ For visited links:nth-child(n)โ Targets nth child element
Pseudo-elements: Style a specific part of an element.
Syntax: selector::pseudo-element
Common pseudo-elements:
::beforeโ Insert content before element::afterโ Insert content after element::first-lineโ Style first line of text::selectionโ Style selected text
Layout Techniques
6. What is Flexbox and how do you use it?
Flexbox (Flexible Box Layout) is a one-dimensional layout system for arranging items in rows or columns with automatic spacing and alignment.
Key properties:
display: flex;โ Enables flexbox on a containerflex-directionโ Row (default) or columnjustify-contentโ Align items along main axisalign-itemsโ Align items along cross axisflex-wrapโ Wrap items to next linegapโ Space between items
Item properties:
flex-growโ Grow to fill available spaceflex-shrinkโ Shrink when space is limitedflex-basisโ Default size before growing/shrinking
Example: .container { display: flex; justify-content: center; align-items: center; }
7. What is CSS Grid and how does it differ from Flexbox?
CSS Grid: A two-dimensional layout system for creating complex page layouts with rows and columns.
Key difference: Flexbox is 1D (rows or columns), Grid is 2D (rows and columns at the same time).
Grid properties:
display: grid;โ Enables grid layoutgrid-template-columnsโ Define column widthsgrid-template-rowsโ Define row heightsgapโ Space between grid cellsgrid-columnandgrid-rowโ Position items
When to use each:
- Flexbox: Navigation bars, lists, single-row/column layouts
- Grid: Page layouts, dashboards, complex multi-row/column designs
Many layouts use both: Grid for page structure, Flexbox for component layouts.
8. Explain the CSS positioning property (static, relative, absolute, fixed, sticky).
The position property determines how an element is positioned in the document flow.
Position values:
- static (default): Normal document flow. Top/left/right/bottom have no effect.
- relative: Positioned relative to its normal position. Still takes up space in the flow.
- absolute: Positioned relative to the nearest positioned ancestor. Removed from document flow.
- fixed: Positioned relative to the viewport. Stays in place when scrolling. Removed from flow.
- sticky: Hybrid of relative and fixed. Acts as relative until scrolling reaches a threshold.
Common use cases:
- Absolute: Dropdowns, tooltips, overlays
- Fixed: Sticky navigation, floating buttons
- Sticky: Section headers that stick when scrolling
9. What is the float property and when should you use it?
The float property was historically used for layout but is now mainly used for wrapping text around images.
Values: left, right, none
Original purpose: Create multi-column layouts. Floated elements remove from normal flow, and other content wraps around them.
Modern approach: Use Flexbox or Grid instead of floats for layout. Floats are outdated for layout purposes.
Still used for: Wrapping text around images.
Common issue: Floated elements collapse parent height. Solution: Use clearfix or overflow: auto; on parent.
Example: <img style="float: left; margin-right: 10px;" src="image.jpg"> to wrap text around image.
10. What is the difference between margin and padding?
Padding: Space inside the element, between the content and the border.
- Uses the element's background color
- Increases the element's total size (unless
box-sizing: border-box) padding: 10px 20px;โ top/bottom 10px, left/right 20px
Margin: Space outside the element, between the element and other elements.
- Transparent (shows background behind it)
- Collapses with adjacent margins (margin collapse)
margin: 10px;โ 10px on all sides
Visual analogy: A picture frame (border) with glass (padding) and space around the frame (margin).
Use padding for: Internal spacing within elements
Use margin for: Space between elements
Responsive Design
11. What are media queries and how do you use them?
Media queries allow you to apply CSS styles based on device characteristics like screen size, orientation, or resolution.
Basic syntax:
@media (max-width: 768px) { /* styles for tablets and below */ }
Common breakpoints:
- Mobile: 0-480px
- Tablet: 481px-768px
- Desktop: 769px-1024px
- Large Desktop: 1025px+
Mobile-first approach: Write styles for mobile first, then add larger screens:
/* Mobile styles first */
.container { width: 100%; }
@media (min-width: 768px) {
.container { width: 750px; }
}
Other media query features: orientation, color, resolution, prefers-dark-mode
12. What is the difference between px, em, rem, and vh/vw units?
Different CSS units serve different purposes and scale differently.
Absolute units:
px (pixels):Fixed size. 1px always equals 1 pixel on screen. Not responsive.
Relative units:
em:Relative to parent's font-size. 1em = parent's font-size. Compounds when nested.rem (root em):Relative to root (html) font-size. 1rem = html font-size. Consistent scaling.vh (viewport height):Percentage of viewport height. 100vh = full screen height.vw (viewport width):Percentage of viewport width. 100vw = full screen width.% (percent):Relative to parent element.
Best practices:
- Use
remfor most measurements (fonts, spacing) โ easier to maintain - Use
pxfor borders and small details - Use
vh/vwfor full-screen layouts - Use
%for responsive containers
13. What is a mobile-first approach and why is it recommended?
Mobile-first design means designing and developing for mobile devices first, then progressively enhancing for larger screens.
How it works:
- Write base styles for mobile (smallest viewport)
- Use
min-widthmedia queries to enhance for tablets and desktops - Add features as screen size increases
Benefits:
- Forces you to prioritize content and functionality
- Better performance (simpler base styles)
- Ensures mobile experience is optimal
- Easier to maintain and scale
Example:
/* Mobile first */
.container { width: 100%; }
@media (min-width: 768px) {
.container { width: 750px; }
}
@media (min-width: 1024px) {
.container { width: 960px; }
}
14. How do you make a website responsive without media queries?
You can create responsive layouts using only modern CSS features without explicit media queries.
Techniques:
- Relative units: Use %, em, rem instead of px. Auto-scales with viewport.
- Flexbox:
flex-wrap: wrap;automatically wraps items on small screens. - CSS Grid:
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));automatically adjusts columns. - max-width: Limits element width, shrinks on smaller screens.
- aspect-ratio: Maintains proportions across screen sizes.
- clamp():
font-size: clamp(1rem, 5vw, 3rem);scales within min/max values.
Example with clamp: padding: clamp(1rem, 5vw, 3rem); automatically scales padding based on viewport.
Note: Media queries are still recommended for optimal control, but these techniques reduce media query dependency.
15. What is the viewport meta tag and why is it important?
The viewport meta tag tells the browser how to render the page on mobile devices.
Essential for responsive design:
<meta name="viewport" content="width=device-width, initial-scale=1.0">
What it does:
width=device-widthโ Set viewport width to device's actual widthinitial-scale=1.0โ Set initial zoom level to 100%
Without this tag: Mobile browsers assume desktop viewport width (980px), causing content to be zoomed out and unreadable.
Additional properties:
minimum-scale=1.0โ Prevent users from zooming too far outmaximum-scale=1.0โ Prevent users from zooming (not recommended โ accessibility)user-scalable=noโ Disable pinch zoom (not recommended)
Advanced CSS
16. What is the difference between transitions and animations?
Transitions: Smooth change from one state to another over time. Triggered by state change (hover, focus, class change).
Syntax: transition: property duration timing-function delay;
Example: .button { background: blue; transition: background 0.3s ease; } .button:hover { background: red; }
Animations: Sequences of changes over time. Can repeat and have multiple keyframes. Don't require a trigger.
Syntax: Define keyframes and apply animation:
@keyframes slide {
from { left: 0; }
to { left: 100px; }
}
.box { animation: slide 1s infinite; }
Key differences:
- Transitions: Require state change, simpler, better for simple effects
- Animations: Independent, more control, better for complex sequences
17. What are CSS variables (custom properties) and how do you use them?
CSS variables (custom properties) allow you to store values and reuse them throughout your stylesheet.
Define variables: --variable-name: value;
Use variables: var(--variable-name)
Example:
:root {
--primary-color: #6D28D9;
--spacing-unit: 8px;
}
.button {
background: var(--primary-color);
padding: var(--spacing-unit) var(--spacing-unit) * 2;
}
Benefits:
- Maintainability โ Change value once, update everywhere
- Consistency โ Same values used throughout
- Dynamic โ Can change with JavaScript:
element.style.setProperty('--primary-color', 'red') - Scoped โ Can be defined locally for specific elements
Note: Variables cascade and inherit like normal CSS properties.
18. What is the BEM (Block Element Modifier) naming convention?
BEM is a naming convention that makes CSS more maintainable, scalable, and easier to understand.
Structure: Block__Element--Modifier
Components:
- Block: Standalone component (e.g.,
card,button) - Element: Part of a block, dependent on the block (e.g.,
card__title) - Modifier: Variation of block or element (e.g.,
button--primary)
Example:
.card { } /* Block */
.card__header { } /* Element */
.card__title { } /* Element */
.card--featured { } /* Modifier on block */
.card__title--large { } /* Modifier on element */
Benefits: Clear naming, avoids specificity wars, easier to maintain, modular approach.
19. How do CSS gradients work and what are the different types?
CSS gradients create smooth color transitions. They're background images, not colors.
Types of gradients:
- Linear Gradient: Colors transition in a straight line
background: linear-gradient(to right, red, blue);- Radial Gradient: Colors transition from center outward
background: radial-gradient(circle, red, blue);- Conic Gradient: Colors rotate around a point
background: conic-gradient(red, yellow, lime, aqua, blue, magenta, red);
Advanced example:
background: linear-gradient(45deg, red 0%, yellow 50%, green 100%);
Common uses: Hero sections, buttons, backgrounds, creative effects.
Note: Gradients are hardware-accelerated and performant compared to multiple background images.
20. What are transform and filter properties and how do they differ?
Transform: Changes the coordinate space of an element. Includes rotate, scale, translate, skew.
Syntax: transform: translateX(50px) rotate(45deg) scale(1.2);
Benefits: Hardware-accelerated, doesn't affect layout, smooth animations.
Filter: Visual effects applied to elements. Includes blur, brightness, contrast, saturate.
Syntax: filter: blur(5px) brightness(150%) contrast(120%);
Key difference:
- Transform: Changes element's coordinate system
- Filter: Changes visual appearance, like a camera filter
Performance: Transform is generally more performant for animations. Use filter for visual effects.
Common filters: blur(), brightness(), contrast(), grayscale(), sepia(), drop-shadow()
21. What is CSS performance and how can you optimize it?
CSS performance affects page load speed, rendering performance, and user experience.
Optimization techniques:
- Minimize CSS: Remove unused code, minify files
- Avoid expensive properties: Avoid box-shadow, text-shadow on many elements
- Use transform and opacity: Hardware-accelerated, performant for animations
- Reduce repaints/reflows: Batch DOM changes, use CSS instead of JavaScript
- Use will-change:
will-change: transform;hints to browser for optimization - Lazy load CSS: Use media queries, split stylesheets
- Avoid expensive selectors: Attribute selectors, universal selectors on large DOMs
Testing: Use Chrome DevTools Performance tab to identify slow rendering.
22. What are CSS blend modes and how are they used?
Blend modes determine how an element's colors interact with the colors below it. Like Photoshop layer modes.
Syntax: mix-blend-mode: multiply;
Common blend modes:
multiplyโ Darkens (like darkening filter)screenโ Lightens (like light)overlayโ Combines multiply and screendarkenโ Keeps darker of two colorslightenโ Keeps lighter of two colorscolor-dodgeโ Brightens and increases contrast
Use cases: Image overlays, creative text effects, photo effects.
Example: .overlay { background: blue; mix-blend-mode: multiply; }
23. What is the difference between @import and link tag for CSS?
Link tag: <link rel="stylesheet" href="styles.css">
- Parallel download โ Browser downloads CSS while parsing HTML
- Better performance
- Preferred method
@import: @import url('styles.css');
- Sequential download โ Browser must download and parse CSS before downloading imported file
- Slower performance
- Can be nested (import within import)
Performance comparison: Link tag is faster because it loads in parallel.
Best practice: Use link tag for external stylesheets. Reserve @import for dynamic or conditional loading.
24. What are CSS counters and how do you use them?
CSS counters are variables that track count across elements. Useful for custom numbering.
How they work:
counter-reset: name;โ Initialize countercounter-increment: name;โ Increment countercounter(name)โ Use counter value
Example:
.container { counter-reset: section; }
h2::before {
counter-increment: section;
content: counter(section) ". ";
}
This creates: "1. Title", "2. Title", "3. Title"
Use cases: Custom numbering (instead of ol), step-by-step guides, chapter numbers.
Nested counters: Can have nested counters like "1.1", "1.2", "2.1"
25. What are container queries and how do they work?
Container queries allow styling elements based on their container's size, not the viewport. Revolutionary for component reusability.
Enable container context: .container { container-type: inline-size; }
Apply styles:
@container (min-width: 400px) {
.card { columns: 2; }
}
Key difference from media queries:
- Media queries: Based on viewport size
- Container queries: Based on parent container size
Benefits: True component isolation, reusable at any size, responsive without knowing viewport.
Example use case: A card component that stacks on small containers and displays side-by-side in large containers, regardless of page viewport.
Browser support: Modern browsers (Chrome 105+, Safari 16+). Progressive enhancement recommended.
Master HTML & CSS.
Build real projects. Get hired.
Join the Best AI Programs โ three 5-month courses, fully online, with placement assistance. Week 1 is free.
Explore our AI-era courses โ