How content, padding, borders, and margins work together to define the size and position of every element on a web page
Every visible element on a web page occupies space in a predictable, structured way. CSS describes that space using a model called the box model. This chapter explains how content, padding, borders, and margins work together to define an element's size and position. Students who understand the box model can predict layout behavior, debug spacing problems, and control page design with precision rather than guesswork.
Open any web page, open developer tools, hover over an element, and the browser highlights it with colored overlays — a region in the center surrounded by three more bands moving outward. Those four bands are the box model, and they apply to every element on every web page you will ever build. This chapter takes that idea apart layer by layer, then shows how to size, debug, and inspect boxes with confidence.
A card on a web page is declared width: 300px, but the browser renders it at 352 pixels wide. A button's text looks cramped against its edges. Two headings that should sit 40 pixels apart on the page are actually only 24 pixels apart. What single idea explains all three of these surprises — and how can a developer prevent them before they happen? By the end of this chapter, you will be able to answer that question precisely, and you will know exactly where to look in your browser to confirm it.
By the end of this chapter, you should be able to:
width and height interact with the box model, including percentage, max-width, and min-width values.box-sizing: border-box simplifies layout calculations, and apply it using the universal selector reset.display: block, display: inline, and display: inline-block change how elements occupy space.overflow property to control content that exceeds its container.Open any web page, open developer tools, hover over an element, and the browser highlights it with colored overlays: a region in the center, surrounded by three more bands moving outward. Those colors represent the four layers of the CSS box model. Every element on every web page is rendered using this same structure.
The CSS box model describes how much space an element takes up and where its edges are. It is not a design choice you make sometimes. It applies to every single element — paragraphs, headings, images, buttons, navigation links, divs, spans, and everything else. Understanding the box model means understanding how the browser builds a page.
Here is the fundamental idea: each element is composed of four nested regions.
Working from the inside out:
width and height measure by default.These four layers are the box model. Every layout calculation in CSS — every width, every gap between elements, every overflowing card — depends on them. The rest of this chapter examines each layer in turn, then shows how they combine to determine an element's true size.
The content area holds the actual content of an element: text, an image, a video, or child elements. When you set width and height on an element using the default box-sizing value (explained fully in Section 14.7), those measurements apply to the content area only — they do not include padding, border, or margin.
With the default box model, this paragraph's content area is 400 pixels wide and 100 pixels tall. If you later add padding or a border, the total visible size of the element will become larger than 400 by 100 pixels.
This is a common source of confusion for beginners. A box that is declared width: 400px does not necessarily occupy 400 pixels of page space. It occupies 400 pixels of content space, plus whatever padding and border are added.
The background color of an element fills both the content area and the padding area. It does not fill the margin.
In this example, the light blue background color covers the content and the 20-pixel padding around it. The 30-pixel margin remains transparent, showing whatever is behind the element — usually the page background.
If you do not set a width, block elements expand to fill their parent container. If you do not set a height, block elements grow to contain their content. This is normal and usually desirable behavior. You do not need to set explicit dimensions on every element.
Padding is the space between an element's content and its border. It is inside the element. It shares the element's background color. It creates breathing room between text and the element's edges.
This paragraph has a light yellow background that extends 20 pixels beyond the text in every direction — top, right, bottom, and left.
CSS padding can be written as a shorthand that applies to all four sides, or you can target each side independently.
You can also write each side as a separate property:
Separate properties are useful when you need to override one side without affecting the others.
Because padding is inside the element under the default box-sizing value, adding padding increases the total space the element occupies.
The content area is 200 pixels wide, but the element's total rendered width is 200 + 20 + 20 = 240 pixels. This is why layout calculations can become surprising. Section 14.7 introduces box-sizing: border-box, which changes this behavior in a way most developers prefer.
Padding is most commonly used to:
The border is a line drawn around the padding and content. It can be visible or invisible. It has three properties: width, style, and color.
These three properties can also be written in one shorthand declaration:
The shorthand order is: width, style, color. The style value is required — without it, the border will not appear even if width and color are set.
The most commonly used styles in production web development are solid and none.
Like padding, borders can target individual sides:
Individual side targeting is useful for design patterns like bottom-only borders on headings, left-border accent lines on blockquotes, or removing borders on specific sides of navigation items.
border-radius rounds the corners of an element's border box.
A border-radius of 50% on an element with equal width and height creates a circle. This is how profile images and icon buttons are styled as circles.
Like padding, border adds to the total rendered size of an element under the default box-sizing setting.
Total width = 200 (content) + 20 (padding left) + 20 (padding right) + 4 (border left) + 4 (border right) = 248 pixels.
Section 14.7 shows how box-sizing: border-box handles this differently.
Margin is the transparent space outside an element's border. It separates the element from its neighbors. Because it is outside the border, it does not share the element's background color — it is always transparent.
This paragraph has 20 pixels of transparent space on all four sides, separating it from neighboring elements.
Margin uses the same shorthand pattern as padding:
Individual margin properties:
One of the most useful applications of margin is centering a block element horizontally inside its parent.
When both margin-left and margin-right are set to auto, the browser distributes the remaining space equally on each side, centering the element. This technique only works when the element has a defined width that is smaller than its parent.
The shorthand for this pattern is:
This sets top and bottom margin to zero, and left and right margin to auto.
Margin collapsing is one of the most confusing behaviors in CSS for beginners. When two block elements are stacked vertically and both have vertical margins, those margins collapse into a single margin equal to the larger of the two — they do not add together.
You might expect the space between a heading and the following paragraph to be 24 + 16 = 40 pixels. Instead, it collapses to the larger value: 24 pixels.
Margin collapsing only occurs between vertical (top/bottom) margins of block elements in normal document flow. Horizontal margins do not collapse. Margins inside flex containers and grid containers do not collapse.
Understanding margin collapsing explains many unexpected spacing results beginners encounter when trying to add space between elements.
Browsers apply default margins to many HTML elements. Headings, paragraphs, lists, and other elements have built-in top and bottom margins that create readable spacing in plain HTML documents. These defaults are often the first thing a stylesheet resets or adjusts.
width and height set the dimensions of an element's content area, under the default box-sizing setting.
A percentage width is relative to the parent element's width.
If the parent is 800 pixels wide, this column will be 400 pixels wide. If the parent is 600 pixels wide, the column will be 300 pixels wide. Percentage widths enable fluid layouts that respond to different container sizes.
max-width sets a maximum size limit. The element will grow to fill available space, but never exceed the maximum.
This is a common pattern for readable body text. On narrow screens the article fills the full width; on wide screens it stops growing at 680 pixels, preventing uncomfortably long lines.
min-width and min-height prevent an element from becoming smaller than a specified size.
This button will always be at least 120 pixels wide, even if its text content is shorter. This prevents small text from creating a disproportionately narrow button.
Setting a fixed height is often risky because content can exceed it.
If the card's content requires more than 200 pixels, the content may overflow its container in unexpected ways. Section 14.9 covers how to handle overflow. In many layouts, it is better to set min-height and let the element grow with its content, or to avoid setting height altogether.
Percentage heights are more complicated than percentage widths. A percentage height only works if the parent element has an explicitly defined height. This catches many beginners by surprise.
For full-height layouts, modern CSS uses viewport units (covered in Chapter 17) or Flexbox and Grid (covered in Chapters 15 and 16) rather than percentage heights on nested elements.
By default, width and height apply only to the content area. Adding padding or borders makes the total element size larger than what you declared. This is called the content-box model, because your width and height describe the content box only.
Most web developers find content-box behavior counterintuitive. When you say "this element should be 300 pixels wide," you usually mean the entire visible element should be 300 pixels, including its padding and border.
CSS provides a property that changes this: box-sizing.
With border-box:
The total rendered width of this card is exactly 300 pixels. The padding and border are included within that 300. The content area becomes 300 − 20 − 20 − 2 − 2 = 256 pixels, calculated automatically by the browser.
Almost every modern web project applies border-box to all elements globally using a universal selector reset. This is now a standard practice.
The * selector targets every element. *::before and *::after target pseudo-elements, which behave like elements but are not in the HTML. This one rule at the top of a stylesheet makes width and height mean what most people intuitively expect them to mean.
After this reset, when you set width: 300px, the element is 300 pixels wide, full stop — padding and borders included.
width: 300px, padding: 24px, and border: 2px solid black.content-box cards at width: 300px would occupy 704 pixels total — overflowing the container. With border-box, they fit comfortably. This is exactly why the global border-box reset is so widely used: it makes layout math straightforward.Not all elements behave the same way in the document flow. CSS recognizes two primary display types that affect how elements participate in the box model.
Block elements:
width, height, margin, and padding on all four sidesCommon block elements: <div>, <p>, <h1>–<h6>, <section>, <article>, <header>, <footer>, <nav>, <ul>, <ol>, <li>, <form>, <blockquote>.
Inline elements:
width and height settingspadding and margin, but top and bottom padding and margin can behave unexpectedly and may not push other block elements awayCommon inline elements: <span>, <a>, <strong>, <em>, <img> (technically inline-block, discussed below), <code>, <abbr>.
Setting width: 200px on an inline element will have no visible effect in most browsers.
display: inline-block is a hybrid. Elements with this value:
width, height, margin, and padding on all four sides, like block elementsThis badge sits inline with text, but has full box model control. Inline-block was heavily used in older CSS layout techniques. Today, Flexbox and Grid are usually preferred for layout, but inline-block remains useful for small inline elements that need padding and sizing.
Any element's display value can be overridden in CSS.
Changing display type is common in navigation menus, button groups, and component styling.
In addition to block, inline, and inline-block, the display property also enables the Flexbox and Grid layout systems:
These values are covered in detail in the next two chapters. The box model you have just learned does not disappear when you start using Flexbox or Grid — it is the foundation every flex item and grid item is still built on.
When content is larger than its container, it overflows. The overflow property controls what happens.
Without setting overflow, content simply flows out of its container if it exceeds the declared size. This is often visible as text or images spilling outside a div with a fixed height.
If the text inside the card requires 300 pixels of height, the text will flow below the card's visible yellow background — it exists in the document but sits outside the card's box.
overflow: hidden clips anything outside the container's box. Content that extends past the edges is simply not displayed.
Common uses for overflow: hidden:
overflow: auto adds scrollbars only when content exceeds the container's dimensions.
This is useful for scrollable log panels, code editors, preview boxes, and any container that should be a fixed height but may contain variable-length content.
Overflow can be controlled independently on each axis.
overflow-x: hidden is often applied to the body or page wrapper to prevent horizontal scrollbars caused by full-width elements.
The browser's developer tools include a visual box model panel that shows the exact computed size of each region for any selected element. Learning to use this panel is one of the most practical debugging skills in web development.
The diagram shows the element's margin (usually in orange), border (usually in yellow/gold), padding (usually in green), and content dimensions (usually in blue), with pixel values labeled in each region.
The numbers in each region show the computed size of that layer. For example:
This tells you the element's content area is 320 by 48 pixels, with 12 pixels of top/bottom padding, 20 pixels of left/right padding, no border, and 16 pixels of margin on all sides.
box-sizing: content-box is in effect, the total width is content + left padding + right padding + left border + right border. Adding the global border-box reset usually simplifies this.margin-top or margin-bottom being inherited from the browser stylesheet, visible in the Styles panel as a crossed-out or grayed-out rule labeled user agent stylesheet.overflow: hidden or overflow: auto as appropriate. If the fixed height is causing problems, consider whether min-height would be a better choice.1. Identify which element looks wrong on the page. 2. Inspect that element in developer tools. 3. Check the box model diagram for its actual computed values. 4. Compare the computed values against what your CSS declares. 5. Look for margin collapse, unexpected browser defaults, or a missing box-sizing setting. 6. Make a small change, save, and inspect again.
This method — inspect, compare, hypothesize, change, verify — is how professional web developers debug layout problems.
width and height measure the content area only, not padding, border, or margin.border-radius. Like padding, borders add to total element size by default.max-width and min-width, and fixed heights carry a real risk of content overflow. Percentage heights require an explicitly sized parent to work.box-sizing: content-box (the default) measures width and height as content only. box-sizing: border-box includes padding and border in the declared size, and is applied almost universally with a selector reset.overflow property controls what happens when content exceeds its container: visible lets it spill out, hidden clips it, and auto adds scrollbars only when needed.*, *::before, *::after { box-sizing: border-box; } that applies border-box sizing to every element.Read each CSS rule carefully before answering the questions that follow it.
box-sizing: content-box?margin: 40px auto do to this element?width: 360px include?.card?.card?A page has an <h2> immediately followed by a <p>.
.preview is taller than 180 pixels?overflow: hidden to overflow: visible make the extra content appear? Where would it appear?A stylesheet does not include a box-sizing reset. Calculate the total rendered width for each element.
Element A
Element B
For each element: What is the total rendered width (content + padding + border, excluding margin)? What is the total horizontal space the element occupies including its margins?
Now apply the global reset:
Recalculate the content area width for each element in Trace 14-1 with border-box now in effect. The total rendered width is fixed at 300 pixels for each.
The page background is white. The container's parent is the <body>. What do you expect to see?
What is the total rendered width assuming content-box?
display value would you need to add to make width and height take effect?Each scenario below describes a layout problem. Identify the likely cause and write a corrected CSS rule.
A student writes this CSS expecting two divs, each declared at width: 50%, to sit side by side inside a 600-pixel container. But together they seem too wide.
What is the total rendered width of each .column with default box-sizing? Why do they not fit side by side? What is the fix?
A student wants a paragraph to have exactly 16 pixels of space above it. They write:
But on the page, there appears to be more space than expected above the first paragraph — it looks like there might be 24 pixels or more. The heading above uses this CSS:
Explain what is happening. What is the actual space between the heading and the paragraph?
A student creates a testimonial card with a fixed height:
Longer testimonials are spilling below the card's yellow background and overlapping the next card. What property and value would clip the overflowing content? What property and value would add a scrollbar instead?
A student is confused because this element seems to ignore its width and height:
The yellow background appears but does not seem to be 200 by 50 pixels. What is the problem, and what two solutions could fix it?
Create a small HTML file with a single .card div containing a heading and two sentences of text. Write a stylesheet that:
box-sizing: border-box resetwidth: 380px, centered with margin: 40px autopadding: 24px inside the cardborder-radius: 8pxInspect the card in developer tools and confirm the total rendered width is 380 pixels.
Create an HTML file with the following elements: a <div> with a visible background, a <span> with a visible background inside a paragraph, and an <a> link styled with padding and a background color.
Observe the difference between how the div, span, and link occupy space. Then: change the link's display to inline-block and add width: 160px; change the link's display to block and observe how it behaves in the paragraph.
Write a brief explanation of what changed and why.
Create a div with width: 300px, height: 150px, and a visible background color. Fill it with enough text to overflow. Then test all four values of overflow (visible, hidden, scroll, auto) one at a time. For each value, write one sentence describing what you observe.
Open any existing web page or one of your own practice pages. Using browser developer tools:
box-sizing reset by looking in the Styles panel for a * or html ruleWrite your observations in a comment at the top of a new CSS file.
These questions connect Chapter 14 to earlier material.
A student adds a CSS rule that should change the background color of all .card elements. But some cards are not changing. They look at the rule and notice an override in a later stylesheet section that is setting background-color: white. Which CSS concept explains why the later rule is winning?
A paragraph has font-size: 18px, line-height: 1.6, and padding: 20px. In your own words, explain the difference between line-height and padding. What does each control?
A student uses <div> for every section of their page. Their layout works, but their page has no semantic landmarks. List three semantic HTML elements from Chapter 6 that could replace some of those <div> elements and explain what meaning each provides.
A .callout box needs: 16 pixels of padding on all sides, a bottom border only (2 pixels, solid, in a medium blue color), and no border on any other side. Write the CSS rules. Use both the padding shorthand and targeted border-side properties.
Spacing and layout choices affect the usability of pages, including for users with different needs.
Buttons and links that are too small are difficult to use, especially on touch screens. Inspect a navigation link or button on a practice page. Does it have enough padding to be comfortably tappable? A general guideline is that interactive elements should be at least 44 by 44 pixels in total rendered size. Measure the element's padding and content in developer tools to check.
When overflow: hidden clips text, sighted users cannot read it — but screen readers may still be able to access it in some configurations. This can cause unexpected experiences. Describe a case where clipping content with overflow: hidden might confuse or mislead a screen reader user, and explain why it is better to simply not show content than to visually hide text that is semantically present.
Wide text columns reduce readability. Research suggests that comfortable reading line length is typically between 45 and 75 characters per line. Using max-width on a text container (often in ch units, where 1ch is the width of the "0" character) can enforce readable line lengths. Write a CSS rule using max-width to limit a paragraph container to approximately 65 characters wide.
box-sizing: border-box reset. Style each card with padding, a border, and a border-radius. Set a fixed width on each card. Use margin to add space between cards — they will stack vertically for now; Chapter 15 covers making them sit side by side.overflow: hidden to prevent any card from growing beyond a defined max-height, if the content overflows.box-sizing: border-box does and why you applied it.Chapter 14 introduced the box model, the fundamental structure that governs how every element occupies space on a page. Now that you understand how individual boxes work, you are ready to learn how to arrange multiple boxes in relation to each other.
Chapter 15 introduces Flexbox, a one-dimensional layout system that controls how child elements are distributed along a row or column. Flexbox solves layout challenges that were difficult or impossible to handle cleanly with margins and inline-block elements alone — including evenly spaced navigation menus, centered card rows, equal-height columns, and flexible responsive sections. The box model is the foundation; Flexbox is the first major tool for building layouts on top of it.