CSS

Fundamentals

1

What is the CSS Box Model?

Every element is a rectangular box with four layers:

box-sizing:

  • content-box (default): Width/height = content only
  • border-box: Width/height includes padding + border

Why is this important?

  • Fundamentally defines how spacing algorithms calculate physical dimensions for every visual component on the screen.
  • Using `border-box` saves UI layouts from instantly breaking or overflowing when a developer simply adds padding.
  • Decouples internal structural white-space (`padding`) from external neighbor-pushing physics (`margin`).
2

What is CSS Specificity?

The algorithm that determines which CSS rule applies when multiple rules match the same element.

Specificity hierarchy (highest to lowest):

  1. !important (avoid)
  2. Inline styles (style="...")
  3. ID selectors (#id)
  4. Class, attribute, pseudo-class (.class, [attr], :hover)
  5. Element, pseudo-element (div, ::before)

Calculation: (ID, Class, Element)

(1, 2, 1) wins over (0, 3, 0) because ID beats classes.

Why is this important?

  • Prevents structural chaos by establishing a deeply mathematical hierarchy for which styling overrides win.
  • Explains exactly why attempting to override a deeply nested `.card #title` tag with just `.header` visually fails.
  • Understanding this immediately prevents developers from toxically abusing `!important` tags to artificially bypass normal cascading logic.
3

What is the CSS Cascade?

The algorithm determining which styles apply, in order of priority:

  1. Origin & Importance:
    • User !important
    • Author !important
    • Author normal
    • User normal
    • Browser defaults
  2. Specificity: Higher specificity wins
  3. Source Order: Later rules win (if specificity is equal)

Why is this important?

  • Provides the mechanical backbone for CSS (Cascading Style Sheets), explaining why properties flow downwards into children.
  • Saves extreme amounts of physical code bytes by allowing parents to universally declare fonts and colors that naturally trickle down.
  • Ensures browsers have a strict, absolute conflict resolution path if two perfectly equal specificities compete.
4

What is the difference between em, rem, %, vh, vw?

UnitRelative To
emParent element's font-size
remRoot element's font-size (:root or html)
%Parent element's size
vh1% of viewport height
vw1% of viewport width
vminSmaller of vh/vw
vmaxLarger of vh/vw
dvhDynamic viewport height (accounts for mobile browser UI)

Why is this important?

  • Replaces static `px` layouts that mathematically explode or refuse to scale on mobile devices with dynamic viewport algorithms.
  • Using `rem` ensures all fonts scale globally and instantly across the app simply by changing the root `html` tag value.
  • The `vh/vw` limits allow drawing perfectly full-screen hero sections without relying upon heavy JavaScript viewport calculations.
5

What are CSS Pseudo-classes and Pseudo-elements?

Pseudo-classes (:) — Select based on state:

Pseudo-elements (::) — Style part of an element:

Why is this important?

  • Transforms CSS from static visual rulesets into dynamic, logic-based interaction listeners (like observing `:hover` or `:focus`).
  • Pseudo-elements (`::before`) eliminate massive DOM bloat by injecting purely decorative icons without needing physical HTML node elements.
  • Eliminates thousands of lines of JavaScript event listeners historically required just to change a button color on mouseover.
6

What is the difference between display: none, visibility: hidden, and opacity: 0?

PropertyRenderedTakes SpaceEventsAccessible
display: noneNoNoNoNo
visibility: hiddenYesYesNoNo
opacity: 0YesYesYesDepends

Why is this important?

  • Solves the physics gap between logically existing in the DOM yet physically leaving zero footprint (`display: none`).
  • `visibility: hidden` allows structurally maintaining a perfect layout grid shape even when specific items are logically invisible to users.
  • `opacity` provides the exact mechanism for rendering visually beautiful soft fade transitions without instantly snapping items in and out of existence.
7

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

PropertyWidth/HeightMargin/PaddingLine Break
inlineNoHorizontal onlyNo
blockYesAll sidesYes
inline-blockYesAll sidesNo

Why is this important?

  • Provides the ability to sit elements beautifully side-by-side (like text) while still permitting strict height/width assignments.
  • Fixes the historic broken block algorithms where purely `inline` spans would totally ignore top-bottom padding assignments.
  • Reduces the constant need for absolute positioning hacks just to make a button cleanly stack natively within surrounding paragraph text.

Positioning

8

Explain CSS position values.

ValueBehavior
staticDefault. Normal document flow.
relativeOffset from normal position. Creates stacking context.
absoluteRemoved from flow. Positioned relative to nearest positioned ancestor.
fixedRemoved from flow. Positioned relative to viewport.
stickyToggles between relative and fixed based on scroll position.

Why is this important?

  • Provides foundational layering control for detaching components completely out of standard linear document constraints.
  • `sticky` entirely deprecated the need for complex scroll-listener JavaScript scripts historically required to pin headers to the top bounds.
  • `absolute` enables complex micro-composites, like attaching a tiny red notification dot specifically to the top-right corner of a generic avatar box.
9

What is the z-index and stacking context?

z-index controls the stacking order of positioned elements (higher = on top).

Stacking context: Created by:

  • Root element
  • position: relative/absolute/fixed with z-index set
  • opacity less than 1
  • transform, filter, perspective
  • isolation: isolate

Gotcha:z-index only works within the same stacking context.

Why is this important?

  • Allows deep, 3D layering priorities across overlapping floating elements like modals, dropdowns, and sticky headers.
  • Explains the extremely confusing 'Stacking Context' bug where a `z-index: 10` object is mathematically trapped underneath a `z-index: 1` component container.
  • Enables safe background manipulation like watermarks without blocking interactive click physics on the topmost visual layers.
10

How do you center an element?

Horizontally center block element:

Horizontally center inline/text:

Flexbox (any direction):

Grid:

Absolute + Transform:

Why is this important?

  • Historically the hardest operation in CSS, modern mechanisms vastly reduce the extreme boilerplate required to simply align elements.
  • Eliminates brutal 'negative margin' math hacks required to put a floating div exactly in the visual middle of a changing screen sizes.
  • Provides highly predictable rendering invariants allowing elements to float beautifully across device resizes without structural breakage.

Flexbox

11

What is Flexbox and when do you use it?

A one-dimensional layout method for arranging items in rows or columns.

Use for: Navigation bars, card layouts, centering, evenly spaced items.

Why is this important?

  • Completely eliminates the archaic, incredibly buggy `float: left` and clearfix architecture historically used for structuring simple rows.
  • Delivers a dynamic, math-free 1D algorithmic layout engine capable of flowing or wrapping an unknown amount of cards effortlessly.
  • Natively supports perfect vertical centering, solving the most notorious physical spacing complaint of the early web era.
12

Explain flex-grow, flex-shrink, and flex-basis.

PropertyDefaultDescription
flex-grow0How much to grow relative to siblings
flex-shrink1How much to shrink relative to siblings
flex-basisautoInitial size before growing/shrinking

Why is this important?

  • Provides elastic physics for components, allowing items like search bars to mathematically consume 'all leftover space' without custom scripts.
  • Prevents massive text blocks from fatally wrapping or collapsing tiny neighbor icons completely via strict shrink limits.
  • Serves as the internal architectural foundation for 'holy grail' fluid layouts like auto-growing central article columns.
13

What is the difference between justify-content and align-items?

  • justify-content: Aligns items along the main axis (horizontal in row, vertical in column)
  • align-items: Aligns items along the cross axis (vertical in row, horizontal in column)

Values:flex-start, flex-end, center, space-between, space-around, space-evenly

Why is this important?

  • Decouples complex visual spacing concerns into two strict, distinct 90-degree vector controls.
  • Allows spreading 3 buttons perfectly to the far bounds of a container `space-between` without requiring manual margin padding math.
  • Simplifies component grouping by instantly collapsing items to the center, top-aligning items, or stretching their baselines vertically match.

Grid

14

What is CSS Grid and when do you use it?

A two-dimensional layout system for rows AND columns simultaneously.

Use for: Page layouts, galleries, dashboard grids, complex two-dimensional designs.

Why is this important?

  • The first structural CSS mechanics designed specifically and inherently for full symmetrical two-dimensional layouts.
  • Eliminates the bizarre 'Flexbox inception' required to build complex macro sites by attempting to forcibly stack rows inside columns inside rows.
  • Separates strict visual placement logic completely from DOM order, allowing mobile layouts to deeply rearrange sections without moving physical HTML tags.
15

Explain fr unit and repeat().

fr (fraction): Distributes available space proportionally.

repeat(): Shorthand for repeating patterns.

Why is this important?

  • The `fr` unit solves fatal percentage-rounding bugs (e.g., three `33.3%` divs visually wrapping because border pixels push them over 100%).
  • Drastically reduces unreadable repetitive boilerplate, transforming a 12-column static math definition into a simple syntax loop.
  • Computes fractional structural divisions perfectly by factoring inside padding and gap gutters naturally.
16

What is the difference between auto-fill and auto-fit?

Both create responsive grids, but behave differently with leftover space:

  • auto-fill: Keeps empty tracks (invisible columns)
  • auto-fit: Collapses empty tracks, items stretch to fill

Why is this important?

  • Unlocks true 'Container Query' physics naturally, allowing grids to intelligently decide how many elements fit without static media breakpoints.
  • `auto-fit` eliminates massive whitespace gaps on extra-wide monitors by mathematically stretching the remaining items organically.
  • Provides the absolute cleanest responsive gallery layouts available without relying upon a single pixel-specific screen breakpoint calculation.

Responsive Design

17

What are Media Queries?

Apply styles based on device characteristics (screen size, orientation, etc.).

Why is this important?

  • The fundamental cornerstone of the entire Responsive Web epoch, destroying the need for separate `m.website.com` mobile codebases.
  • Provides dynamic conditional rulesets for rendering specific layouts based purely on the physical attributes hitting them.
  • Enables powerful accessibility hooks like observing OS-level `prefers-reduced-motion` or `prefers-color-scheme` settings.
18

What is Mobile-First vs Desktop-First?

Mobile-First: Start with mobile styles, add complexity for larger screens.

Desktop-First: Start with desktop styles, remove/simplify for mobile.

Mobile-first is preferred: Progressive enhancement, better performance on mobile.

Why is this important?

  • Prevents extreme data usage by fundamentally halting mobile devices from accidentally downloading massive desktop background images before overriding them.
  • Forces minimalistic, essential design thinking upfront rather than attempting to horribly squish a massive desktop layout vertically.
  • Saves considerable performance cycles as mobile browsers parse baseline linear rules immediately without reading through heavy desktop exception blocks.
19

What are Container Queries?

Apply styles based on a container's size (not viewport).

Use case: Reusable components that adapt to their container, not the viewport.

Why is this important?

  • Solves the fatal flaw of Component architectures where a generic 'Card' component structurally shatters if dropped in a narrow sidebar versus a wide main view.
  • Decouples component responsiveness completely from the absolute browser Viewport, shifting physics limits strictly onto their physical parent container.
  • The ultimate endpoint for true Modular Design ecosystems, allowing components to be published perfectly isolated and self-aware.

Modern CSS

20

What are CSS Custom Properties (Variables)?

User-defined properties that can be reused throughout the stylesheet.

Why is this important?

  • Eliminates 'Find and Replace' CSS maintenance nightmares by centralizing major color and spacing values into global runtime variables.
  • Empowers instant dynamic toggling—like Light vs Dark mode switching—by fundamentally flipping the variable palette instantly inside the browser.
  • Unlocks JavaScript to cleanly interact directly with CSS layout systems simply by updating a native DOM style variable instead of overwriting classes.
21

What is the clamp() function?

Sets a value that scales between a minimum and maximum.

Related functions:

  • min(): Returns smallest value
  • max(): Returns largest value

Why is this important?

  • Reverses the incredibly dense chain of media query font breakpoints required for scalable text into a single mathematically limited line.
  • Ensures headers are mathematically bound to never physically break a mobile layout (`min`), while never blowing out obnoxiously large on 4k monitors (`max`).
  • Smoothly interpolates structural padding scaling perfectly linearly during browser resizes without sudden jarring visual snapping.
22

What are CSS Logical Properties?

Properties that adapt to writing direction (LTR/RTL).

PhysicalLogical
margin-leftmargin-inline-start
margin-rightmargin-inline-end
margin-topmargin-block-start
padding-leftpadding-inline-start
widthinline-size
heightblock-size

Why is this important?

  • Permanently fixes the massive layout breakage of Internationalization (i18n) when converting English sites into exact Right-to-Left languages like Arabic.
  • Replaces rigid physical constraints (`left`, `top`) with dynamic flow properties (`inline-start`, `block-start`).
  • Massively speeds up complex translations and vastly lowers codebase bloat since RTL layouts no longer require an entirely overridden separate stylesheet.
23

What is aspect-ratio?

Maintains a proportional relationship between width and height.

Before aspect-ratio (padding hack):

Why is this important?

  • Eliminates the horrific and notorious 'padding-bottom percentage hack' traditionally required to make a responsive YouTube iframe retain its shape.
  • Prevents 'Cumulative Layout Shift' (CLS) penalty loops during page load by forcefully carving out the exact structural footprint before the heavy image fully downloads.
  • Maintains perfect 1:1 symmetrical layout geometry dynamically without relying on absolute pixel heights.

Animations & Transitions

24

What is the difference between Transitions and Animations?

Transitions: Animate between two states (requires trigger like :hover).

Animations: Complex, multi-step, can run automatically.

Why is this important?

  • Eliminates incredibly heavy, thread-blocking JavaScript loop dependencies traditionally required just to slide open menus linearly.
  • Offloads complex keyframe visual states directly to the incredibly optimized browser rendering engine, resulting in buttery smooth user experiences.
  • Provides the micro-interactions necessary to clearly communicate interface context physically moving rather than instantly teleporting state blocks.
25

What is transform and why is it performant?

Applies 2D/3D transformations without triggering layout.

Performance:transform and opacity are GPU-accelerated (compositor only), avoiding expensive reflows/repaints.

Why is this important?

  • Prevents highly destructive, laggy 'layout thrashing' triggers which force browsers to recalculate the entire physical page layout maths.
  • Provides native GPU hardware acceleration, guaranteeing silky smooth 60 Frames-Per-Second animations visually entirely independent from the main JavaScript thread.
  • Enables complex mathematical 3D rendering manipulations like rotating elements in space natively.
26

What are CSS Animation performance best practices?

  1. Animate only transform and opacity (GPU-accelerated)
  2. Use will-change sparingly

  3. Prefer CSS over JavaScript for simple animations
  4. Use prefers-reduced-motion

  5. Avoid animating layout properties (width, height, top, left)

Why is this important?

  • Explains the physics behind why animating properties like `margin` or `width` instantly ruins battery life and shutters low-end mobile CPUs entirely.
  • Guides developers into the 'Composite' render phase optimizations via strictly animating exclusively `opacity` and `transform` states.
  • Forces developers to respect user settings via `prefers-reduced-motion` mechanics to prevent accessibility/vertigo triggers.

Advanced Topics

27

What is BEM methodology?

Block Element Modifier — A naming convention for CSS classes.

Why is this important?

  • Solves the fatal nightmare of deep UI CSS collision breakage in extreme scale monolithic codebases by generating universally unique class signatures.
  • Vastly flattens specificities safely to a strict level of 1, effectively murdering the horrific unresolvable `!important` conflict loops of early eras.
  • Directly correlates class string arrays entirely 1:1 with modular JavaScript framework component logical structures.
28

What are CSS Preprocessors (Sass, Less)?

Tools that extend CSS with features like variables, nesting, mixins, and functions.

Sass example:

Modern alternative: CSS custom properties + PostCSS can replace many preprocessor features.

Why is this important?

  • Permitted features like loops, variables, and extreme modularity heavily decades before native specifications officially absorbed them.
  • Drastically enhanced extreme CSS developer velocity architectures utilizing nested rule blocks and deep color math functions.
  • Enabled extreme component fragmentation workflows natively merging hundreds of micro partials safely down into simple single output payloads.
29

What is CSS-in-JS?

Writing CSS directly in JavaScript (styled-components, Emotion, etc.).

Pros: Scoped styles, dynamic styling, co-located code. Cons: Runtime cost, larger bundle, learning curve.

Why is this important?

  • Utterly obliterates dead-code global CSS collisions by mathematically scoping styles exclusively identically to their executing JS code logic boundaries.
  • Permits unbelievably dynamic inline theme interpolations based entirely around extremely complex React/Vue internal state execution loops.
  • Removes the heavy cognitive load of maintaining completely separate logic mapping linkages between `.js` components and detached global `.css` class pools.
30

What are CSS Layers (@layer)?

Control the order of specificity without increasing selector complexity.

Order matters: Later layers override earlier layers, regardless of specificity within the layer.

Why is this important?

  • Represents the absolute endgame of Specificity war resolution, allowing massive overarching structural priority overrides outside of normal hierarchy algorithms.
  • Utterly trivializes third-party CSS library imports by mathematically permanently depressing generic Bootstrap rules far underneath the custom layer.
  • Massively simplifies microfrontend styling conflict collision mitigation entirely via native encapsulation bounds.