EasyConcept

What is the CSS box model?

Technology:
CSS
Experience:
Intern,
Junior
Topics:
CSS Layout

Quick answer

Every element is a box made of content, padding, border and margin. The default content-box size counts only the content; border-box includes padding and border in the width you set.

Detailed explanation

From the inside out: content (the text or image), padding (space inside the border), border, then margin (space outside the border). Adjacent vertical margins collapse into the larger of the two, which surprises people building stacked cards.

With box-sizing: content-box (the default), width: 200px is the content only, so padding and border make the element wider. box-sizing: border-box makes width include padding and border, which is why most teams set *, *::before, *::after { box-sizing: border-box; }.

Example

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

.card {
  width: 320px;       /* includes padding and border */
  padding: 16px;
  border: 1px solid #ddd;
  margin-bottom: 16px;
}
  • CSSEasy

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

    Block elements start on a new line and take the full available width; inline elements sit in the text flow and ignore width and height; inline-block sits in the flow but accepts width, height, padding and margin on all sides.

    Intern 路 Junior 路 CSS Layout
  • CSSMedium

    What is the difference between Flexbox and CSS Grid?

    Flexbox is one-dimensional (a row or a column). CSS Grid is two-dimensional (rows and columns at once). Use Flexbox for alignment along a line; use Grid when the layout is a real 2D structure.

    Junior 路 Mid-level 路 CSS Layout
  • CSSMedium

    How does CSS specificity work?

    Specificity is the score the browser uses to decide which rule wins: inline styles beat IDs, IDs beat classes/attributes/pseudo-classes, and those beat elements. When scores tie, the last rule in the source wins.

    Junior 路 Mid-level 路 CSS Layout