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.
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.
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.
/* 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
styleattribute 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.
| Selector | Example | Matches |
|---|---|---|
| Type | p | Every <p> |
| Class | .btn | Elements with class="btn" |
| ID | #header | The element with id="header" |
| Attribute | input[type="email"] | Email inputs |
| Descendant | .nav a | Links anywhere inside .nav |
| Child | .list > li | Direct children only |
| Pseudo-class | a:hover, li:nth-child(2) | Elements in a state or position |
| Pseudo-element | p::first-line, .btn::before | A 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-visibleshows 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:
- Origin and importance:
!importantdeclarations beat normal ones. - Cascade layers (
@layer), if you use them. - Specificity: the more specific selector wins.
- Source order: if everything else is equal, the rule written later wins.
Specificity#
Think of specificity as a score with columns: inline, IDs, classes, elements. Compare from left to right; the first column that differs decides.
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.
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#
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.
*,
*::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.
| Value | Behaviour |
|---|---|
block | Starts on a new line and fills the available width. |
inline | Flows with text; width and height are ignored. |
inline-block | Flows with text but accepts width, height and vertical spacing. |
flex | Makes a one-dimensional flex container. |
grid | Makes a two-dimensional grid container. |
none | Removes 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;topandlefthave 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.
.card { position: relative; }
.card .badge {
position: absolute;
top: 12px;
right: 12px;
}
.site-header {
position: sticky;
top: 0;
z-index: 10;
}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 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) orcolumn.justify-content: alignment on the main axis (flex-start,center,space-between,space-around,space-evenly).align-items: alignment on the cross axis (stretchby 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: 1means "grow and share space equally".
/* 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.
/* Responsive card grid with no media queries */
.cards {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
gap: 20px;
}- The
frunit shares out free space.1fr 2frmakes the second column twice as wide. minmax(240px, 1fr)keeps each column at least 240px wide.auto-fillcreates as many columns as fit, so the grid reflows by itself.
Named areas for page layouts#
.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; }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#
| Unit | Relative to | Good for |
|---|---|---|
px | Fixed | Borders, small details |
rem | Root (html) font size | Font sizes and spacing that respect user settings |
em | The element's own font size | Padding that scales with a button's text |
% | The parent | Fluid widths |
vw / vh | The viewport | Full-screen sections |
dvh | The dynamic viewport | Mobile 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.
.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()#
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.
.card-wrapper { container-type: inline-size; }
@container (min-width: 400px) {
.card { display: flex; gap: 16px; }
}Modern CSS features#
Custom properties (CSS variables)#
: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#
.card {
padding: 16px;
& h3 { margin-top: 0; }
&:hover { box-shadow: 0 4px 16px rgb(0 0 0 / 0.1); }
}Transitions and animations#
.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-boxglobally. - Use
gapinstead 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.
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-widthmedia queries,clamp()and container queries. - Use custom properties for themes and animate
transformandopacity.