Skip to main content
1:1 mock interviews with Sumit, scored on a real hiring rubric.Book a slot →

CSS Complete Guide: Box Model, Specificity, Flexbox, Grid and Responsive Design

Learn CSS in depth: selectors, the cascade and specificity, the box model, Flexbox, Grid, positioning, responsive design, modern CSS features and best practices, with examples.

jiocoder TeamUpdated Oct 7, 20268 min readCSS
CSS Complete Guide: Box Model, Specificity, Flexbox, Grid and Responsive Design

CSS (Cascading Style Sheets) controls how HTML looks: colours, spacing, fonts, layout and animation. This guide explains the ideas that make CSS predictable, the cascade, specificity and the box model, and then shows how to build real layouts with Flexbox, Grid and responsive techniques.

Before you start

CSS styles HTML, so a solid HTML base helps. If you need a refresher, read our HTML complete guide first.

How CSS works#

A CSS rule has a selector that picks elements and a declaration block of property and value pairs.

CSS
/* selector */
.card {
  /* property: value; */
  padding: 16px;
  border-radius: 12px;
  background: #ffffff;
}

Three ways to add CSS#

  • External stylesheet: <link rel="stylesheet" href="styles.css">. Best for real projects, because it is cached and reused across pages.
  • Internal: a <style> tag in the <head>. Fine for single pages and demos.
  • Inline: a style attribute on an element. Hard to maintain and very high specificity, so avoid it except for dynamic values.

Selectors#

Selectors decide which elements a rule applies to. These are the ones you will use every day.

SelectorExampleMatches
TypepEvery <p>
Class.btnElements with class="btn"
ID#headerThe element with id="header"
Attributeinput[type="email"]Email inputs
Descendant.nav aLinks anywhere inside .nav
Child.list > liDirect children only
Pseudo-classa:hover, li:nth-child(2)Elements in a state or position
Pseudo-elementp::first-line, .btn::beforeA part of an element, or generated content

Modern selectors worth knowing#

  • :is() and :where() group selectors. :where() always has zero specificity, which makes it great for resets.
  • :has() is the "parent selector". .card:has(img) styles cards that contain an image. It is supported in all modern browsers.
  • :focus-visible shows focus rings for keyboard users without showing them on every mouse click.

The cascade, specificity and inheritance#

When several rules set the same property on the same element, the browser picks a winner using the cascade. It compares, in order:

  1. Origin and importance: !important declarations beat normal ones.
  2. Cascade layers (@layer), if you use them.
  3. Specificity: the more specific selector wins.
  4. Source order: if everything else is equal, the rule written later wins.

Specificity#

CSS specificity ladder from element selectors to classes, IDs, inline styles and !important

Think of specificity as a score with columns: inline, IDs, classes, elements. Compare from left to right; the first column that differs decides.

CSS
p              { color: black; } /* 0-0-0-1 */
.intro         { color: blue;  } /* 0-0-1-0 */
p.intro        { color: green; } /* 0-0-1-1  wins over .intro */
#hero .intro   { color: red;   } /* 0-1-1-0  wins over all above */
  • Classes, attribute selectors and pseudo-classes all count in the class column.
  • Element selectors and pseudo-elements count in the element column.
  • The universal selector * and combinators (>, +, space) add nothing.
  • One ID beats any number of classes. That is why ID selectors make CSS hard to override.
Avoid specificity wars

Style with classes, keep selectors short and avoid IDs and !important in your stylesheets. If you find yourself adding !important to beat another rule, lower the specificity of the other rule instead.

Inheritance#

Some properties pass from parent to child automatically. Text properties such as color, font-family, font-size and line-height inherit. Box properties such as margin, padding, border and width do not. You can force behaviour with the keywords inherit, initial and unset.

The box model#

CSS box model diagram with content, padding, border and margin layers

Every element is a rectangular box made of four layers, from the inside out:

  • Content: the text or image.
  • Padding: space inside the border. It takes the element's background.
  • Border: the line around the padding.
  • Margin: transparent space outside the border that pushes other elements away.

box-sizing: content-box vs border-box#

By default (content-box), width sets only the content width, and padding and border are added on top. A 300px box with 20px padding and a 2px border is actually 344px wide. With border-box, the width includes padding and border, which is far easier to reason about.

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

Margin collapsing#

Vertical margins between block elements collapse: a 24px bottom margin next to a 16px top margin gives 24px of space, not 40px. It does not happen inside Flexbox or Grid containers, which is one reason many developers use gap instead of margins for spacing.

Display and normal flow#

The display property sets how a box behaves in the layout.

ValueBehaviour
blockStarts on a new line and fills the available width.
inlineFlows with text; width and height are ignored.
inline-blockFlows with text but accepts width, height and vertical spacing.
flexMakes a one-dimensional flex container.
gridMakes a two-dimensional grid container.
noneRemoves the element from the layout and from screen readers.

Note the difference between display: none, which removes the element completely, and visibility: hidden, which hides it but keeps its space.

Positioning#

The position property takes an element out of normal flow or offsets it.

  • static (default): normal flow; top and left have no effect.
  • relative: offsets the element from its normal spot, and keeps its original space. It also becomes the anchor for absolutely positioned children.
  • absolute: removed from flow and placed relative to the nearest positioned ancestor.
  • fixed: placed relative to the viewport; stays put on scroll.
  • sticky: acts like relative until a scroll threshold, then sticks like fixed inside its parent.
CSS
.card { position: relative; }
.card .badge {
  position: absolute;
  top: 12px;
  right: 12px;
}
.site-header {
  position: sticky;
  top: 0;
  z-index: 10;
}
z-index and stacking contexts

z-index only works on positioned elements (and flex or grid items). A parent with transform, opacity below 1 or its own z-index creates a new stacking context, and children can never escape it. If a high z-index "does nothing", check the parents.

Flexbox#

Flexbox main axis and cross axis with justify-content, align-items, gap and flex-wrap

Flexbox lays items out in one direction, a row or a column. Everything depends on two axes: the main axis (the direction set by flex-direction) and the cross axis (perpendicular to it).

Container properties#

  • flex-direction: row (default) or column.
  • justify-content: alignment on the main axis (flex-start, center, space-between, space-around, space-evenly).
  • align-items: alignment on the cross axis (stretch by default, center, flex-start, flex-end, baseline).
  • flex-wrap: lets items move onto new lines.
  • gap: space between items.

Item properties#

  • flex-grow: how much an item grows to fill extra space.
  • flex-shrink: how much it shrinks when space is short.
  • flex-basis: its starting size before growing or shrinking.
  • The shorthand flex: 1 means "grow and share space equally".
CSS
/* Navbar: logo left, links right, vertically centred */
.navbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 24px;
}

/* Perfect centring */
.center {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
}

CSS Grid#

Grid works in two dimensions at once: rows and columns. Define the tracks on the container and the items fall into cells.

CSS
/* Responsive card grid with no media queries */
.cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  gap: 20px;
}
  • The fr unit shares out free space. 1fr 2fr makes the second column twice as wide.
  • minmax(240px, 1fr) keeps each column at least 240px wide.
  • auto-fill creates as many columns as fit, so the grid reflows by itself.

Named areas for page layouts#

CSS
.page {
  display: grid;
  grid-template-columns: 240px 1fr;
  grid-template-areas:
    "header header"
    "sidebar main"
    "footer footer";
  gap: 16px;
}
.page header { grid-area: header; }
.page aside  { grid-area: sidebar; }
.page main   { grid-area: main; }
.page footer { grid-area: footer; }
Flexbox or Grid?

Use Flexbox when content decides the layout in one direction: navbars, button groups, centring. Use Grid when you want to control rows and columns together: page layouts, card galleries, dashboards. Most real pages use both.

Units#

UnitRelative toGood for
pxFixedBorders, small details
remRoot (html) font sizeFont sizes and spacing that respect user settings
emThe element's own font sizePadding that scales with a button's text
%The parentFluid widths
vw / vhThe viewportFull-screen sections
dvhThe dynamic viewportMobile full-height sections that respect browser bars

Responsive design#

Responsive design makes one page work on every screen size. Start with the viewport meta tag in your HTML, then build mobile first: write base styles for small screens and add min-width media queries for larger ones.

CSS
.grid { display: grid; gap: 16px; }

@media (min-width: 768px) {
  .grid { grid-template-columns: repeat(2, 1fr); }
}

@media (min-width: 1024px) {
  .grid { grid-template-columns: repeat(3, 1fr); }
}

Fluid type with clamp()#

CSS
h1 {
  /* never smaller than 2rem, never larger than 3.5rem */
  font-size: clamp(2rem, 1.2rem + 3vw, 3.5rem);
}

Container queries#

Media queries react to the viewport. Container queries react to the size of a component's parent, so the same card can adapt in a sidebar and in the main column. They are supported in all modern browsers.

CSS
.card-wrapper { container-type: inline-size; }

@container (min-width: 400px) {
  .card { display: flex; gap: 16px; }
}

Modern CSS features#

Custom properties (CSS variables)#

CSS
:root {
  --brand: #2563eb;
  --radius: 12px;
}
.btn {
  background: var(--brand);
  border-radius: var(--radius);
}
[data-theme="dark"] {
  --brand: #60a5fa;
}

Unlike Sass variables, custom properties live in the browser, cascade and can change at runtime, which makes them ideal for themes and dark mode.

Native nesting#

CSS
.card {
  padding: 16px;

  & h3 { margin-top: 0; }
  &:hover { box-shadow: 0 4px 16px rgb(0 0 0 / 0.1); }
}

Transitions and animations#

CSS
.btn {
  transition: transform 150ms ease, background-color 150ms ease;
}
.btn:hover { transform: translateY(-2px); }

@keyframes fade-in {
  from { opacity: 0; }
  to   { opacity: 1; }
}
.toast { animation: fade-in 200ms ease-out; }

@media (prefers-reduced-motion: reduce) {
  * { animation: none !important; transition: none !important; }
}

Animate transform and opacity where you can. The browser can animate them without recalculating layout, so they stay smooth.

Best practices#

  • Use a consistent naming method, such as BEM (.card__title--large), or a utility framework like Tailwind CSS.
  • Keep specificity low: prefer single classes over long selectors and IDs.
  • Set box-sizing: border-box globally.
  • Use gap instead of margins between flex and grid items.
  • Respect accessibility: keep text contrast readable, never remove focus outlines without a replacement, and honour prefers-reduced-motion.
  • Test on real devices and use browser DevTools to inspect the box model and grid overlays.
Next steps

Test yourself with our CSS interview questions for freshers, then move on to the JavaScript complete guide.

Key takeaways#

  • The cascade decides between rules: importance, layers, specificity, then source order.
  • Specificity is scored as inline, IDs, classes, elements; keep it low by styling with classes.
  • Every element is a box of content, padding, border and margin; use border-box.
  • Use Flexbox for one-dimensional layouts and Grid for two-dimensional layouts.
  • Build mobile first with min-width media queries, clamp() and container queries.
  • Use custom properties for themes and animate transform and opacity.