Skip to lesson content
Web Technologies โ€บ Level 12
LEVEL 12 ยท CSS

CSS Box Model and Layout

Calculate component sizes, follow the page flow and keep every explanation readable.

๐Ÿ“ฆ Box model๐Ÿ“ Sizing๐ŸŽฏ Beginner โ†’ Intermediate๐Ÿงช Lab + MCQs
01

Learning Objectives

Level 11 explained which CSS declarations apply. This lesson explains how their sizes and layout choices affect the space a component needs. You will separate content, padding, border and margin; compare box-sizing modes; follow normal flow; and recognize when overflow or positioning is causing a problem.

Build a workshop card with predictable dimensions and enough room for readable content. Use a controlled box lab to compare declared width with the actual border-box width, then explain a layout issue without hiding the content.

Box parts

Identify each layer and its purpose.

Sizing

Calculate a simple horizontal box and use size constraints.

Flow

Understand how ordinary blocks and inline content are arranged.

Diagnosis

Check overflow, positioning and containing space before adding overrides.

02

The Box Model โ€” Four Different Areas

For the block-box examples here, think of four nested areas. Content is the space for text or other children. Padding is the space between that content and the border. The border surrounds the padded area. Margin is space outside the border.

These areas answer different questions. Increase padding when text is too close to the card edge. Increase a margin or a layout gap when separate cards are too close to each other. Changing one can affect the required size, but it does not make the other areas interchangeable.

A background ordinarily paints behind content and padding and extends under the border by default; margin itself is outside that background. The visible color behind a margin often comes from another element. A margin is not an extra colored wall attached to the card.

Read from inside to outside
Content

The actual text or child content area.

Padding + border

Breathing room around content, then a visible or invisible boundary.

Margin

Outside spacing relative to neighboring content.

03

Content Dimensions โ€” State What width Means

In the ordinary content-box mode, width specifies the content width. The browser then adds horizontal padding and borders to produce the border-box width. A 200px content width does not automatically mean a 200px card from outside border to outside border.

The example calculations use a block box, symmetric pixel values, a definite width and no min/max constraints or layout-driven shrinking. Those assumptions keep the arithmetic clear. A real layout can impose further constraints that change the used size.

.card {
  box-sizing: content-box;
  width: 200px;
  padding: 20px;
  border: 4px solid #173451;
}

Predict: 200px content plus 40px horizontal padding plus 8px horizontal border produces a 248px border box. Margin, if any, is considered outside that border box.

Height also depends on content, line wrapping and sizing rules. Do not infer a fixed height merely from a stated width; a narrower text area can wrap into more lines.

04

Padding โ€” Space Inside the Boundary

Padding separates content from the border. It is useful for readable panels, buttons and input controls. A four-value padding shorthand follows top, right, bottom and left. Two values mean vertical then horizontal padding; one value applies to all four sides.

.notice { padding: 12px 20px; }
.card { padding: 10px 16px 20px 24px; }

Padding contributes to the box dimensions. In content-box mode, adding it enlarges the border box beyond a stated content width. In border-box mode, it consumes space within the stated border-box width and can reduce the space left for the content.

Padding cannot be negative. When padding needs to depend on writing direction, logical properties such as padding-inline and padding-block express inline and block axes rather than fixed left/right assumptions. Use physical directions for the arithmetic in this lesson and logical properties where the component needs to adapt.

05

Borders and Outlines โ€” Different Purposes

A border surrounds the content and padding. Its width contributes to the box dimensions; its style and color define its appearance. A border declaration normally needs a visible style, such as solid, to paint a visible boundary.

.card { border: 2px solid #bdd5e6; border-radius: 12px; }
button:focus-visible { outline: 3px solid #126d96; outline-offset: 3px; }

An outline does not occupy space in the box model in the same way a border does. It is useful for focus indicators because showing focus need not push neighboring content. Check that an outline remains visible rather than being clipped by a surrounding overflow rule.

Border-radius rounds corners; it does not change an elementโ€™s semantic meaning. A rounded div remains a div. Increasing border width can change a content-box cardโ€™s outer size, so inspect it when two components unexpectedly stop fitting side by side.

06

Margins, Gaps and Collapsing

Margins separate a box from other content. A layout gap separates items or tracks in a supported layout such as Flexbox or Grid. Decide whether spacing belongs to an individual component or to the container arranging the components.

In normal block flow, some vertical margins can collapse rather than add. Two adjacent positive vertical margins of 20px and 30px can produce a 30px collapsed margin under the relevant conditions. Horizontal margins do not collapse in that way, and margins of flex or grid items do not collapse with each other.

Margin collapsing also has parent/child and empty-block cases. Do not memorize โ€œall margins collapse.โ€ Borders, padding and formatting contexts can change the situation. If a parent appears to move when its first child gains a top margin, inspect those conditions.

.stack { display: flex; flex-direction: column; gap: 16px; }
.stack > .card { margin: 0; }

This example assigns spacing to the container. It avoids relying on adjacent child vertical margins for the stack. A later lesson will explore Flexbox alignment in detail.

07

Worked Calculation โ€” A Content-Box Card

Use the same values consistently: width 200px, padding 20px on each side, border 4px on each side and margin 10px on each side. There is no layout-driven shrinking or min/max constraint in this example.

Content width = 200px
Horizontal padding = 20px + 20px = 40px
Horizontal border = 4px + 4px = 8px
Border-box width = 200px + 40px + 8px = 248px
Border box plus horizontal margins = 248px + 10px + 10px = 268px

The last line measures the horizontal space for this simple box plus its two margins. It is not a universal formula for collapsed vertical spacing or every layout algorithm.

If you set width: 100% on a content-box child and add padding and borders, the required border box can exceed the intended containing width. This is a common reason a panel appears wider than its parent. Check the box-sizing mode rather than simply hiding the overflow.

08

border-box โ€” Include Padding and Border in the Width

With box-sizing: border-box, the declared width describes the border box. Padding and border fit inside that declared size. Margin remains outside it. Using the previous values, a 200px border box leaves 152px for content after subtracting 40px padding and 8px border.

.card {
  box-sizing: border-box;
  width: 200px;
  padding: 20px;
  border: 4px solid #173451;
  margin: 10px;
}
/* Content width: 200 - 40 - 8 = 152px
   Border box + horizontal margins: 200 + 20 = 220px */

Border-box does not include margin and does not make oversized padding disappear. The content size cannot become negative; extremely large padding and border can still force a larger minimum border box. The lab uses values well within the declared width so the simple subtraction is valid.

A common project foundation is box-sizing: border-box for elements and pseudo-elements. That is a chosen styling convention, not a claim that every browser element starts in exactly the same mode.

09

Width Constraints โ€” Flexible Does Not Mean Unbounded

Width, min-width and max-width describe related constraints. A component may grow to the available size but stop at a sensible maximum. Width: 100% with border-box helps a simple card include its padding and border within the intended width.

.card {
  box-sizing: border-box;
  width: 100%;
  max-width: 40rem;
  margin-inline: auto;
  padding: 1.25rem;
}

Auto inline margins can center this constrained block when there is available inline space in this ordinary case. They are not a universal โ€œcenter anythingโ€ switch across all layouts.

Min-width can prevent shrinking. A long unbroken token can also influence a flex or grid itemโ€™s automatic minimum size. When a column refuses to shrink, inspect the minimum and the content. A targeted min-width: 0 on the relevant item can help it shrink; text wrapping or a local scroller may still be needed.

Height, Wrapping and Content Growth

Let ordinary text panels grow with their content. A fixed height that looks correct for one sentence can clip a longer explanation, a translated label or enlarged text. Use min-height when a baseline size is useful while still allowing growth.

.explanation { min-height: 8rem; height: auto; }
.long-token { overflow-wrap: anywhere; }

A height percentage needs a relevant definite basis under the applicable layout rules. Height: 100% is not always โ€œfill the screen.โ€ Viewport units describe viewport-related sizes, while parent-based percentages follow their own resolution rules.

Wrapping affects height because the same text can occupy more lines in a narrower box. Verify both the width and the readable content flow before trying to force a panel into a matching fixed height. For examples with large code lines or tables, a local horizontal scroller may be more suitable than forcing every token to wrap.

10

Normal Flow โ€” Start with the Document Order

Normal flow is the ordinary arrangement of content before you introduce other layout or positioning behavior. Block boxes in typical horizontal writing appear one after another in the block direction. Inline content flows along lines and wraps when the line needs more room.

A paragraph can become taller when its text wraps, and following content naturally moves down. This behavior is useful for learning pages because explanations vary in length. Absolute positioning every paragraph removes that cooperation and makes overlap likely.

Keep a logical source order for reading and keyboard use. Visual rearrangement alone does not necessarily change the order encountered by assistive technology or focus. A good layout starts with meaningful HTML in a sensible sequence.

11

Block, Inline and Inline-Block

Block

A typical block participates as a block in normal flow. Width and height can apply under the relevant box rules.

Inline

Text-level content participates in line layout. Ordinary non-replaced inline boxes do not treat width/height like a block box.

Inline-block

A box participates in the inline flow while providing a box that can accept dimensions.

Context

The element type and display value are related but different. A semantic element can have a changed display value.

.badge { display: inline-block; padding: 4px 10px; }

Images and some other replaced elements have additional sizing behavior. Avoid turning the shorthand โ€œinline ignores sizeโ€ into a rule for every possible element. For text spans, use an appropriate box type when a real sized box is needed.

12

display โ€” Outer Flow and Inner Layout

Display affects how a box participates in its surrounding layout and how its children are arranged. A flex or grid container introduces a layout for its direct items, while the container still has a role in its parentโ€™s layout.

Display: none removes the elementโ€™s boxes from layout. Visibility: hidden normally preserves its layout space while hiding it. Opacity: 0 makes it transparent but does not by itself remove its layout, focusability or interaction. These differences matter for hidden panels and keyboard controls.

.actions { display: flex; gap: 12px; }
.cards { display: grid; gap: 16px; }

A visually hidden control must not remain an unexplained keyboard stop. Choose the appropriate hidden-state behavior for the component and keep its accessible state synchronized. CSS appearance alone is not an accessibility strategy.

13

Overflow โ€” Preserve Access to the Content

Overflow occurs when content extends beyond an applicable box. Overflow: visible permits it to extend; hidden clips it; auto can provide scrolling when needed. Clip also clips, with different scrolling behavior from hidden. Choose based on how the learner should reach the content.

A table or long code sample can use a local horizontal scrolling wrapper. That avoids making the whole page wider while preserving the information. Make the scroller usable by keyboard where needed and keep a visible focus indicator.

.code-scroller { max-width: 100%; overflow-x: auto; }
.code-scroller:focus-visible { outline: 3px solid #126d96; }

<!-- HTML -->
<div class="code-scroller" tabindex="0" aria-label="Scrollable code example">
  <pre>Long code example goes here.</pre>
</div>

Do not use overflow: hidden as a general repair for unreadable or oversized teaching content. First find the incorrect size, automatic minimum or unbroken token. Clipping may remove the exact information the learner needs to read.

14

Positioning โ€” Flow, Containing Blocks and Scrolling

static / relative

Static uses normal positioning. Relative offsets a box while its original place in flow remains reserved.

absolute

Takes the box out of normal flow and positions it using its containing block. Other content does not automatically reserve its place.

fixed

Usually uses the viewport as its reference, but some ancestors can establish a different containing block.

sticky

Participates in flow, then is constrained by its scrolling context and containing area when an applicable inset is set.

.card { position: relative; }
.card .badge { position: absolute; top: 12px; right: 12px; }
.section-label { position: sticky; top: 1rem; }

The relative card establishes the expected reference for the badge in this simple example. Leave enough room so the badge does not cover the title. For sticky behavior, inspect the scroll container, available travel space and inset. An ancestorโ€™s overflow can change which scrolling context matters.

Z-index orders boxes within stacking rules; a huge number does not automatically escape a lower ancestor stacking context. For a lesson header, measure the header and reserve room for content instead of piling larger z-index values onto overlapping panels.

15

Choosing a Layout โ€” Flow First, Flexbox or Grid When Needed

Use ordinary flow for a reading sequence. Use Flexbox when arranging items along a main axis is central, such as a row of actions or a vertical stack. Use Grid when you want an explicit track arrangement across rows and columns. Both can wrap or create additional structure, so โ€œone-dimensionalโ€ and โ€œtwo-dimensionalโ€ describe their design focus rather than an absolute limit on where boxes can appear.

For a row of buttons, the parent can supply display: flex, gap and wrapping. For a card collection, a grid can supply column tracks and gaps. Do not use absolute positioning to imitate a whole ordinary card layout unless the task genuinely needs that arrangement.

.actions { display: flex; flex-wrap: wrap; gap: 12px; }
.cards { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 16px; }

This is an introduction to choosing the tool. Level 13 will develop Flexbox, Grid and responsive design in detail, including alignment and how the track layout changes on smaller screens.

16

Premium Visualizer โ€” Build the Box

Follow the content-box arithmetic, then compare the same declared width in border-box mode. Select a stage or use playback. Each stage states the meaning of the measured width so content size and outside space are not confused.

CSS BOX MODEL TRACE
Step 1 of 5
STEP 01

Start with the content width

This content-box example begins with a definite 200px content width.

Content width = 200px

What is happening?

The demonstration uses symmetric pixel values with no layout shrinking or min/max constraints.

17

Premium Interactive โ€” Box Size Lab

Change the sizing mode and symmetric horizontal values. The preview draws a local block box; the calculated result describes the stated model. It is not a measurement of every possible real CSS layout. This lab deliberately avoids shrinking, min/max constraints and negative content widths.

The pale outer wrapper helps you see the margin space. The cyan area is padding, the dark line is the border and the blue inner area is content. If the preview is narrower than the example, scroll inside the preview to see it; the fixed sizes are teaching values, not a suggested mobile page layout.

Default content-box example: 200px content, 248px border box and 268px including horizontal margins.

Calculated widths for this example

CSS supplied to the preview

18

Debugging Layout โ€” Find the Constraint

Measure the right area

Inspect content, padding, border and margin separately in the browser box-model tools.

Check constraints

Look at width, min/max sizes, box-sizing and automatic minimums.

Follow the flow

Find out whether the box is in normal flow, a flex/grid item or absolutely positioned.

Preserve information

Locate the overflow cause before clipping or hiding the content.

For a card wider than its parent, check whether width: 100% describes content-box width plus extra padding and border. For a column that will not shrink, check an automatic minimum and long unbroken content. For a footer covered by another panel, check whether a positioned element has left normal flow.

For a sticky label that does not stick as expected, inspect the relevant ancestor scrolling context and whether there is room to move. For clipped text after a font increase, inspect a fixed height or overflow rule.

Change one condition at a time and verify the user-visible result. Avoid making an entire course header or footer part of a broad component override. A successful fix keeps the learning content readable and the page navigable.

19

Interview Questions โ€” Flip to Explain

QUESTION

Does border-box include margin?

Click or press Enter to explain
ANSWER

No. The declared border-box width includes content, padding and border. Margin remains outside it.

QUESTION

Why can width: 100% overflow in content-box mode?

Click or press Enter to explain
ANSWER

The declared width describes content. Horizontal padding and borders can add to that width and exceed the intended container space.

QUESTION

Is padding the same as margin?

Click or press Enter to explain
ANSWER

No. Padding is inside the border around content; margin is outside the border relative to surrounding boxes.

QUESTION

Do two adjacent vertical margins always add?

Click or press Enter to explain
ANSWER

No. Some vertical margins collapse in normal block flow. The conditions matter; horizontal margins and flex/grid item margins do not follow that same collapsing rule.

QUESTION

Does absolute positioning reserve space for its box?

Click or press Enter to explain
ANSWER

No. It removes the box from normal flow, so other flow content does not automatically reserve its space.

QUESTION

Why might a flex item refuse to shrink?

Click or press Enter to explain
ANSWER

Its automatic minimum or long unbroken content may constrain it. Inspect the relevant item; a targeted min-width: 0 and suitable wrapping or scrolling may help.

QUESTION

Why is overflow: hidden a poor general fix for a lesson panel?

Click or press Enter to explain
ANSWER

It may clip the explanation. Find the incorrect sizing or content constraint and preserve a way to read all information.

QUESTION

What does a sticky element need?

Click or press Enter to explain
ANSWER

A relevant non-auto inset, an appropriate scrolling context and room within its containing constraints. Ancestor overflow can affect the behavior.

20

MCQ Practice โ€” Calculate and Explain

PRACTICE

1. Which sequence goes from inside to outside?

PRACTICE

2. A content-box width is 200px, padding is 20px per side and border is 4px per side. What is the border-box width?

PRACTICE

3. The same box has 10px margins per side. What is its simple horizontal border-plus-margin space?

PRACTICE

4. In border-box mode with width 200px, padding 20px per side and border 4px per side, what is the content width here?

PRACTICE

5. Which remains outside a border-box width?

PRACTICE

6. What does padding: 12px 20px mean?

PRACTICE

7. Which statement about margin collapsing is correct?

PRACTICE

8. What happens to an absolutely positioned boxโ€™s normal-flow reservation?

PRACTICE

9. Which approach preserves an oversized code example?

PRACTICE

10. Which hidden state normally preserves layout space?

PRACTICE

11. Why can a fixed-height explanation become unreadable?

PRACTICE

12. Which is a suitable next step when a column refuses to shrink?

21

Extra Practice โ€” Specific Dimensions and Behaviors

Content-box calculation

Use width 160px, padding 10px and border 2px per side. Expected border box: 184px; with 10px margins per side: 204px.

Border-box comparison

Keep those values but set border-box. Expected content width: 136px; border box: 160px; with horizontal margins: 180px.

Padding boundary

Set padding to 0px, then 20px with content-box width 200px and border 4px. Expected border widths: 208px then 248px.

Margin separation

Change only margin from 0px to 20px per side. Expected: content and border widths are unchanged; horizontal outside spacing increases by 40px.

Long code

Put a long code line in a local overflow-x auto wrapper. Expected: information remains available inside the wrapper without making the whole lesson wider.

Position comparison

Offset a relative badge, then compare an absolute badge inside a relative card. Expected: relative retains its flow place; absolute needs deliberate space planning.

Text growth

Double an explanationโ€™s text length and increase font size. Expected: an auto-height panel grows rather than clips.

Reading order

Build a title, explanation, lab and summary in source order. Expected: layout styling preserves a useful reading and keyboard sequence.

22

Quick Revision

Layers: Content โ†’ padding โ†’ border โ†’ margin.
Content-box: Add horizontal padding and border to a declared content width.
Border-box: Padding and border fit within the declared border-box width.
Margin: Outside spacing is not included in border-box width.
Padding: Internal breathing room also affects dimensions.
Flow: Ordinary content can grow and move following content naturally.
Growth: Prefer flexible text panels to arbitrary fixed heights.
Overflow: Keep a usable route to all content.
Position: Absolute and fixed positioning do not reserve ordinary flow space.
Diagnosis: Inspect constraints, context and actual box dimensions.
23

Glossary โ€” Flip to Learn

TERM

Content box

Click to see meaning
DEFINITION

Content box

The area allocated to the elementโ€™s content.

TERM

Padding

Click to see meaning
DEFINITION

Padding

Space between the content and the border.

TERM

Border box

Click to see meaning
DEFINITION

Border box

The area including content, padding and border.

TERM

Margin

Click to see meaning
DEFINITION

Margin

Spacing outside the border relative to surrounding layout.

TERM

box-sizing

Click to see meaning
DEFINITION

box-sizing

The property that changes what a declared width or height includes.

TERM

Normal flow

Click to see meaning
DEFINITION

Normal flow

The ordinary arrangement of content under the applicable formatting rules.

TERM

Containing block

Click to see meaning
DEFINITION

Containing block

The reference area used for certain sizes and positioning calculations.

TERM

Overflow

Click to see meaning
DEFINITION

Overflow

Content extending beyond the relevant box area.

TERM

Margin collapsing

Click to see meaning
DEFINITION

Margin collapsing

The combining of certain vertical margins under specific normal-flow conditions.

TERM

Stacking context

Click to see meaning
DEFINITION

Stacking context

A grouping within which stacking order is resolved as part of the pageโ€™s stacking rules.

24

Final Challenge โ€” A Readable Workshop Card

Create a workshop card with a heading, explanation, prerequisites and a native disclosure. Use border-box, readable padding, a visible border and a flexible maximum width. Let the text determine the required height. Put any genuinely long code sample inside a local scrolling wrapper.

Write down a fixed-size test case before switching to a flexible layout: choose width 200px, padding 20px and border 4px. Explain both the content-box and border-box calculations, then verify the browserโ€™s box-model display. State the assumptions that make the numbers meaningful.

Add a small absolute badge inside a relatively positioned card only if you can keep it clear of the title and enlarged text. Use normal flow for the rest of the content. Test a narrow viewport and keyboard focus, and ensure no footer or lesson content is covered.

Success criterion: explain the four areas, predict the simple widths, preserve access to all text and identify the actual cause of a layout problem. Level 13 will extend this work with Flexbox, Grid and responsive design.

25

Level 12 Complete?

Before marking complete, compare both box-sizing modes, calculate the stated example, preserve a long code line without clipping, and explain a normal-flow versus positioned layout choice. Completion stores a local study milestone; it is not an assessment score.