Box Model Interactive Canvas Visualization
CSS Box Model
The CSS Box Model is a concept where every HTML element is represented as a rectangular
box consisting of four main parts.
This model is one of the fundamental building blocks of web design and is critical for
understanding page layout.
Box Model The Invisible Geometry of the Web
The first truth we must accept when starting web design is this: "Everything on a web page is a rectangle."
A round button, a complex logo, or even a single letter—all are actually drawn by the browser inside an invisible rectangular box.
The browser calculates these boxes with millimeter precision, positions them, and stacks them layer by layer to create the interface we see.
The set of rules that determine how this box behaves, how much space it takes, and how it interacts with its neighbors is called the CSS Box Model.
Invisible Geometry and Calculation LogicThis model is not just a width and height setting—it is the "Physics" of the web page.
The space an element occupies on screen is not limited to the width or height values you write.
In the background, the browser combines the content area, padding, borders, and margins to calculate the total size, and this calculation determines the page layout.
Therefore, understanding the Box Model is the foundation for understanding not just visual layout, but also layout stability, overflow problems, and responsive design behavior.
Most Common Misconception: Size PerceptionThe biggest mistakes when calculating an element's total size come from misunderstanding this model's layers ( Padding, Border, Margin ).
The most common misconception, especially for beginners, is thinking that a given width value represents the box's outer boundary; in fact, it usually refers only to the content area.
Layered Structure: 4 Core ComponentsThe Box Model consists of 4 main layers from the center outward. Think of it like an "Onion" or a "House" surrounded by a fence.
At the innermost layer is the content, followed by the padding that protects it, the border that surrounds it, and on the outermost layer the margin that sets the distance from other elements.
Although each of these layers may seem simple on its own, together they form a powerful system that determines the entire geometry and behavior of the web page.
Mental Model ShiftSo far we have learned the layers of the Box Model one by one.
However, the biggest mistake in CSS is assuming this system works exactly like real-world physics.
In the real world, an object's width represents its outer boundary.
But in CSS, width by default does not control a box's outer size—it only controls the content area.
So when you give a box width: 200px, you are actually telling the browser:
"Reserve exactly 200px of space for the text and images inside this box."
Layers like Padding and Border are added not inside this area, but outside it.
This is why in CSS, a box's "visible size" does not often match the values you write.
Understanding this difference is the most critical turning point in the Box Model topic.
Because without establishing this mental model correctly, it is impossible to properly understand layout, responsive design, and alignment systems.
Common MisconceptionsMost of the mistakes made when learning the CSS Box Model stem from misunderstanding some fundamental concepts.
As long as these misconceptions are not corrected, layout problems become inevitable.
Wrong: width determines the box's total width.
Correct: By default it only determines the content area.
Wrong: margin and padding are the same thing.
Correct: Padding is inside the box and is painted; margin is entirely a transparent outer space.
Wrong: Margins always add up.
Correct: On the vertical axis, margin values can collapse (Margin Collapse).
Wrong: Border is just a visual line; it does not take up space.
Correct: Border has physical thickness and is included in the total size.
Catching these misconceptions early prevents most of the problems that occur in CSS before they even arise.
Why Is This Topic Critical?The CSS Box Model is not just a theoretical topic—it is one of the most critical building blocks of modern web design.
Because without understanding the actual space an element occupies on screen, it is impossible to position it correctly or make it work harmoniously with other elements.
The Flexbox and Grid systems used today rely entirely on the correct calculation of these boxes' dimensions.
If the box's actual width is miscalculated, even the most perfect layout system will break unexpectedly.
The same applies to responsive designs.
Ekran boyutu değiştikçe kutuların nasıl davranacağını belirleyen şey, bu modelin doğru anlaşılmasıdır.
Otherwise, elements overflow, alignments break, and the design becomes uncontrollable.
Therefore, understanding the Box Model means not just learning one CSS topic, but unlocking the fundamental logic of all layout systems.
Content The Living Center and Heart of the Box
The innermost layer and starting point of the Box Model ( Box Model ) is the Content ( Content ) area.
When you create an HTML element ( p tag, div, or img ), the "information" that is the element's reason for existing lives here.
The text visitors read, the images they view, the icons they click, or the videos they watch physically reside in this area.
All other layers ( Padding, Border, Margin ) are actually supporting elements that exist to protect, emphasize, and separate this valuable content—without content, the box has no purpose.
Therefore, the content area is the center of the box not only visually but also semantically; the real value in terms of SEO, accessibility, and user experience is produced here.
For the browser, a box's reason for existing is the data it carries; all other layers regulate how that data is presented.
Technical Behavior and Sizing Logic:Most of the confusion when sizing an element in CSS originates from this layer.
When you give the browser a width or height value, the default behavior is to size only this content area.
So you are actually controlling not the box's outer boundaries, but only the usable area inside.
For example: When you give a box width: 300px, the browser will know that width is being specified, and you are effectively telling it: "Make the 'writable area' where text and images fit exactly 300 pixels."
However, this does not mean the total area the box will occupy on screen will be 300 pixels.
If you later add padding ( padding ) or border ( border ) to this box, these additions are applied outward from the 300-pixel content area, and the box begins to grow visually (expand).
Bu durum, özellikle hassas layout tasarımlarında (örneğin grid veya kolon sistemlerinde) beklenmeyen taşmalara ve hizalama problemlerine yol açabilir.
Therefore, the Content Area is the "zero point" where box calculations are made.
Ayrıca içerik alanı dinamiktir; eğer boyut ( width/height ) belirtmezseniz, içerik alanı içindeki verinin yani salt metin veya resim verisinin
( the length of the text or the size of the image ).
This behavior is a result of HTML's flow-based structure; as content increases the box expands or overflows, and as it decreases the box shrinks.
If content is not kept under control, it can exceed the box boundaries, and in that case overflow behaviors come into play.
Padding (İç Boşluk) Tasarımın Nefes Alanı ve İç Konforu
Padding, the second layer of the Box Model, is the strategic "buffer zone" between the Content and the outer boundary, the Border.
Although it may seem like just a distance technically, in design terms Padding functions as an "air cushion" that prevents cramped layouts.
On a web page, when text or images are flush against the edges of their container, it creates a cramped and cluttered feeling for the reader.
Padding pushes content toward the center and gives it the space it deserves.
This way, the design moves from a cramped warehouse look to a spacious, gallery-like layout.
Role: Readability and InteractionPadding's most fundamental role is to provide visual hierarchy and readability.
The eye struggles to follow text that sits too close to the edges.
Padding softens the reading experience by "giving the text room to breathe."
But its role is not only aesthetic; it is also vital for User Experience.
For example: Consider a button: Even if the text inside is small, you can expand its clickable area (touch target) by giving the button higher padding values.
This makes using buttons much easier, especially on touch-based mobile devices.
Critical Property:Padding accepts color or pattern from the background and becomes visible; margin is completely transparent—it does not show the background, it shows the element beneath it.
The background color (background-color) or background image you give an element extends from the content area to the end of the Padding area.
So when you paint a box red, the space around the content also turns red.
This property is the strongest proof that Padding "belongs inside the box."
Analogy: Winter Coat and "Padding" EffectTo fully grasp the concept of Padding, let us set aside technical terms and examine a familiar everyday object: the "Puffer Jacket."
The layers of this coat match the working principle of the CSS Box Model exactly.
Your Body (Content): "You"—your body—sitting at the innermost part of the coat, the coat's reason for existing, is the Content area in CSS.
Just as the coat takes your shape, the box is shaped by its content's size.
The Coat's Outer Fabric (Border): The coat's windproof, waterproof outermost layer or its seams are the Border boundary in CSS.
This layer determines where the coat (the box) ends and where the outside world begins.
Lining and Fiber Filling (Padding): This is the magic part—the soft fiber filling or cotton lining between your body and the coat's outer fabric that keeps you warm is Padding in CSS.
Critical Point of the Analogy:The filling is part of the coat, and if you add more fiber to your coat ( increase the Padding value ), your body ( Content ) does not grow; but the coat itself looks puffier and bulkier from the outside.
It keeps you away from the harshness of the outer fabric and creates a comfortable buffer zone in between.
Just as a red coat's lining is also red, this filling material shares the coat's color and texture; it cannot be thought of separately.
Padding is a filling material that expands the box from the inside outward and gives it volume.
Border The Box's Boundaries and Visual Frame
Border, the third layer of the Box Model from center outward, is the formal boundary between the box's inner world ( Content + Padding ) and the outside world.
Just as Padding is a "buffer zone", Border is the "wall" or "shell" that surrounds it.
This is usually the layer that makes where an element starts and ends visibly clear.
When we want to separate a button from the background, draw attention to an alert box, or frame a form, Border comes into play.
Role: Separation and IdentityBorder's primary role is to rescue content from chaos and draw a frame around it.
Just like a wooden frame around a table, Border focuses the content and isolates it from the rest of the page.
Also, thanks to the border-radius property that came with CSS3, these boundary lines do not have to be right angles; they can be rounded to achieve modern, soft designs ( pill-shaped buttons or circular profile images ).
Critical Property: Thickness That Changes the MathThe most common mistake regarding Border is thinking it does not take up space.
Yet Border has physical thickness.
In Box Model calculations, Border is included in the box's total width and height.
Mathematical Fact:If you have a box 100 pixels wide ( width: 100px ) and add a 5-pixel border ( border-width: 5px ), the total area your box occupies on screen is no longer 100 pixels but 110 pixels.
( 100px Content + 5px Left Wall + 5px Right Wall ). This small difference is the most common cause of side-by-side boxes wrapping to the next line.
Analogy: The House's Brick WallsTo fully grasp the concept of Border and its effect on size calculation, let us think like an architect and look down at a house plan from above.
Content (The House's Rooms): The net usable area inside your house where you place furniture, walk, and live ( net square footage ) is the Content area in CSS.
When we say width, we actually mean this room's width.
Padding (Clearance): You do not push your furniture ( Content ) flush against the walls; you leave space in between for comfortable movement.
This distance between the furniture and the wall is Padding—it is inside the room but is not furniture.
Border (Brick Walls): This is the critical point: Border is the house's walls themselves.
When drawing a line on paper we do not care about its thickness, but in real construction walls are built from brick or concrete and have physical thickness.
If you have a 100-square-meter room and build it with 50 cm thick stone walls, the total area the house occupies on the lot ( gross area ) will be more than 100 square meters.
The thicker you build the walls ( increase border-width ), the more space your house occupies on the lot and the more it expands outward.
The room inside the house ( Content ) does not grow, but the house's total outer perimeter ( Rendered Size ) does.
Margin (Dış Boşluk) Elementin Kişisel Alanı ve Sosyal Mesafesi
Margin, the fourth and outermost layer of the Box Model, is an invisible shield that begins where the element ends (after the Border) and creates distance between it and neighboring elements.
If Padding is an element's "inner peace," then Margin is the element's "external relations."
Margin is the force on a web page that prevents paragraphs from sticking together, ensures boxes are lined up neatly, or keeps a block in the center of the page away from the edges.
Elements without a Margin value will stick together shoulder to shoulder like passengers on a crowded bus; this destroys both readability and aesthetics.
Function: Isolation and PositioningThe primary job of Margin is to push, and when you give an element margin-top: 20px, you are essentially telling that element: "Push your neighbor above you 20 pixels away."
This allows us to manage the spaces on a page that we call "Negative Space" ( White Space ), which gives the eyes a rest.
Furthermore, Margin possesses another special power: the power of "Centering." When we give a box a width and set margin: auto, the browser balances the left and right spacing and places the box exactly in the center of the page.
Critical Feature: Absolute Transparency and the "Paint" PrincipleWhen you want to create space in web design, you are faced with two options: Padding and Margin.
Both move elements away from each other and technically create "white space."
However, there is a fundamental difference of "Matter and Space" between the way the browser renders these two areas, which changes the fate of the design.
Understanding this difference is the most important step toward CSS mastery.
Padding: The Painted Area (Expansion of the Canvas)Padding is included in the element's "flesh"; think of it as a painter who doesn't have enough canvas and expands the drawing area by sewing extra fabric to the edges—that is exactly what Padding is.
Background Continuity: If you give a box a background color ( background-color ) or a background image ( background-image ), the browser starts painting from the content area and continues until the end of the Padding area.
Visual Integrity: Padding is not transparent (you cannot see through it); it carries the element's own color.
Therefore, if you think the text inside a button is too close to the edges and add padding, the button's color will expand along with that space, making the button look larger and more voluminous.
Padding increases the physical body of the object.
Margin: Transparent Area (The Invisible Shield)Margin, on the other hand, is never included in the element's "flesh" or "body."
It is the Negative Space around the element.
Absolute Transparency: You can never apply color to the Margin area; this is one of the key differences from padding. Even if you say background: red; for margin, this command will not work.
Margin is literally "transparent"; it is like glass.
What Do We See? The color you see through the margin gap is not the element's own color; it is the color of the surface ( Parent Element or Body ) on which the element sits.
Function: Margin does not enlarge the object; it moves the object in space or pushes others away.
It is not like a painter expanding their canvas ( Padding ), but like picking up the easel and moving it to another corner of the room ( Margin ).
Analogy: The House Garden and "Fence Distance"You can think of Margin as the "Space Outside the Garden Wall" or the "Fence Distance" between you and your neighbor.
Your House (Content + Padding + Border): This is your living space; it is painted, it belongs to you, and you can control its dimensions.
Garden Distance (Margin): It begins where the house wall ends; this area is still under your control ( no one can build a structure here ), but you cannot build a room here.
If you leave a 5-meter margin (distance) between you and your neighbor, neither your house nor the neighbor's house gets bigger; only the breathing space between the two buildings increases.
Margin ensures that buildings stand like orderly housing blocks, rather than shanties crammed together.
Advanced Note: Margin CollapseIn CSS, margin values usually work as expected; meaning the distance between two elements is thought of as the sum of the given margin values.
However, in certain cases, instead of adding these values, the browser merges them (collapses them) and an unexpected result emerges.
This behavior is called Margin Collapse and it is one of CSS's most confusing, yet most important, "invisible rules."
In the simplest scenario, let's consider two block elements stacked on top of each other.
When you give the top element margin-bottom: 30px and the bottom element margin-top: 20px, most developers expect these two spaces to add up to 50px.
However, in reality, the browser does not add these values; it only considers the largest one.
So the result becomes 30px, not 50px.
This happens because the browser is trying to optimize vertical spacing.
Instead of two separate gaps, the browser leaves a single gap to create a cleaner and more consistent flow.
However, this optimization often leads to unexpected results for the developer.
Margin Collapse occurs not only between sibling elements, but also between parent and child elements.
If there is no padding, border, or content at the top of a parent element, the margin-top value of the first child inside it will spill outside the parent.
In this case, even though the margin appears to belong to the child element, it actually pushes the entire box down.
Similarly, the margin-bottom value of the last child element can also spill outside the parent.
This behavior is the most common answer to the question "why is this gap coming from here?" especially when creating a layout.
An important rule is this: Margin Collapse only occurs in the vertical direction.
That is, margin-left and margin-right values never merge.
Also, collapse does not happen in every situation.
If padding, border, or a new blocking context (such as overflow: hidden) comes between them, this behavior stops.
In other words, there must be no physical layer between the margins for them to merge.
Although Margin Collapse might seem like an error at first glance, it is actually a deliberate part of CSS's flow model.
Understanding this behavior is one of the most critical steps to gaining control over complex layout structures.
|
Value Count
|
CSS Code
|
Description
|
|---|---|---|
Single Value
|
padding: 20px;
|
20px padding is applied to all sides. |
Two Values
|
padding: 10px 30px;
|
10px padding for vertical (top-bottom) and 30px for horizontal (right-left) axes. |
Four Values
|
padding: 5px 10px 15px 20px;
|
Applied as Top: 5px, Right: 10px, Bottom: 15px, and Left: 20px. |
|
Value Count
|
CSS Code
|
Description
|
|---|---|---|
Single Value
|
margin: 20px;
|
20px external spacing is applied to all sides. |
Two Values
|
margin: 10px 30px;
|
10px margin for vertical (top-bottom) and 30px for horizontal (right-left) axes. |
Four Values
|
margin: 5px 10px 15px 20px;
|
Applied as Top: 5px, Right: 10px, Bottom: 15px, and Left: 20px. |
Special Value
|
margin: auto;
|
Used to horizontally center an element (the element must have a defined |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Modern Box Model Examples</title>
<link rel="stylesheet" href="style.css?v=1.0.150">
</head>
<body>
<h2>1. Modern Card Design</h2>
<div class="card">
<h3>Product Title</h3>
<p>
This box is an example of a modern card.
Thanks to <strong>padding</strong>, the text does not stick to the edges.
Thanks to <strong>border-radius</strong>, the corners are not sharp.
</p>
<button
style="padding: 10px 20px; background: #3498db; color: white; border: none; border-radius: 4px; cursor: pointer;">Buy
Now</button>
</div>
<h2>2. Centered Box on Page (Margin Auto)</h2>
<div class="container-box">
<h3>I Am Centered!</h3>
<p>No matter if you widen or narrow the screen, I always stay centered. The magic of <code>margin: 0 auto</code>!</p>
</div>
<h2>3. How Does a Square Box Become a Circle?</h2>
<div class="avatar-box">
LOGO
</div>
</body>
</html>
*,
*::before,
*::after {
box-sizing: border-box;
}
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background-color: #ecf0f1;
margin: 0;
padding: 40px;
}
h2 {
color: #2c3e50;
border-left: 5px solid #e74c3c;
padding-left: 10px;
margin-bottom: 20px;
}
.card {
background-color: #fff;
width: 300px;
padding: 25px;
border: 1px solid #ddd;
margin-bottom: 50px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
border-radius: 8px;
}
.container-box {
background-color: #34495e;
color: white;
width: 80%;
max-width: 600px;
margin: 0 auto;
padding: 20px;
text-align: center;
border-radius: 10px;
}
.avatar-box {
width: 100px;
height: 100px;
background-color: #e67e22;
color: white;
display: flex;
align-items: center;
justify-content: center;
font-weight: bold;
border: 5px solid #fff;
border-radius: 50%;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
margin: 40px auto;
}
Mathematical Trap and the Modern Solution Box-sizing Architecture
We have examined the components of the Box Model ( Content, Padding, Border ) individually.
However, once these parts combine to form a whole, the most confusing and error-prone process in web design begins: "Size Calculation."
At this stage, the developer is no longer just solving a visual problem, but a mathematical one as well.
Expected Logic vs. CSS RealityWhen an architect says, "The width of this room will be 5 meters," they expect the thickness of the walls to remain within those 5 meters—meaning the total plot should not exceed 5 meters.
This is the most intuitive approach; however, in the default world of CSS, logic works in reverse.
In web design, the code you write ( width: 200px ) does not always match the result you see on the screen.
This is because CSS interprets the measurement you provide not as the outer boundary of the box, but solely as the content area.
The Outward Expansion ProblemAs you add padding or a border to enhance the element, the box begins to swell, expanding beyond the dimensions you specified.
In other words, instead of including these additions within the existing width, the browser adds them to the outside, increasing the total size.
This causes unexpected shifts and alignment errors, especially in layouts where multiple elements are aligned side-by-side ( grid systems, column structures ).
Consequences and Critical ImpactThis situation, which forces designers to struggle with pixels and causes boxes to drop to the next line because they no longer fit, lies at the heart of the Box Sizing architecture.
This problem is not just a visual glitch; it also brings issues regarding layout stability and predictability.
This is exactly where the box-sizing property comes into play, changing the default behavior of CSS and giving control back to the developer.
The Problem The Default Model (content-box) and the Addition Logic
The calculation method that has existed since the birth of web browsers and is accepted as the CSS standard is the content-box model.
The logic in this model is based on the principle of "Outward Expansion."
When you give the browser the width: 200px ( Width: 200 pixels ) command, the browser interprets this instruction in a very specific way:
"The developer wants the net content area where text or images will fit to be exactly 200 pixels." The browser fulfills this command and reserves 200 pixels for the content.
However, the problem begins with the additions you make to enhance the design.
If you add padding to this box, saying "The content is too close to the edges, let's have some space," or if you add a border saying "Let's have a line around it"; the browser does not try to fit these new values inside the 200 pixels.
On the contrary, it adds them on top of the 200 pixels; meaning your box begins to swell and expand outward with every new value you provide.
Mathematical Trap Calculation: A Concrete ExampleLet's examine this abstract "expansion" problem through a scenario simulated with real numbers.
Suppose our goal is to create an elegant box that occupies exactly 200 pixels of width on the page, we begin writing our code:
Starting Point (Width): First, we write width: 200px. In the default model, the browser interprets this as, "Let the inner reservoir where only the text fits be 200 pixels," and the box is currently 200 pixels wide.
Adding Padding: We add padding: 20px so that the text doesn't stick to the edges.
Unless specified otherwise in CSS, this value is applied to all four corners.
Since the width calculation is done on a horizontal plane, a total of 40px of "swelling" is added to the box—20px on the Left and 20px on the Right.
Adding a Border: We add border: 5px to define the boundaries of the box.
Just like padding, these walls also occupy physical space.
An additional thickness of 10px is added—5px from the Left and 5px from the Right.
Result and Disappointment:When the browser creates ( renders ) the page, it performs a simple addition:
200px ( Content ) + 40px ( Total Padding ) + 10px ( Total Border ).
The result on the calculator is 250 pixels.
Even if you insist in your code editor that "This box should be 200 pixels," the browser physically reserves 250 pixels for this box on the screen.
This 50-pixel deviation is enough to break the entire layout in a precisely calculated web design.
Why Does It Break the Design? (Layout Breakage)A 50-pixel expansion might not be a problem for a box standing alone.
However, modern web designs consist of boxes ( columns ) lined up side-by-side.
For example: Imagine you give two boxes 50% width each to divide the screen into two equal parts, and this width value is mathematically
50% + 50% = 100%, and the boxes fit perfectly side-by-side.
But in the default model, if you add even a 1-pixel border to these boxes, the equation is ruined:
50% + 50% + 2px ( Borders ) = 100% + 2px.
Since the total width exceeds the screen, there is only one thing the browser can do: Push the box on the right to the next line.
This calculation method is the fundamental reason why designs "explode" or "shift."
A Modern and Rational Solution: The border-box Model The Border-box Model
Professional web developers don't want to reach for a calculator to "add padding, subtract border" for every single design.
To eliminate this constant calculation struggle and ensure the stability of the layout, they change the CSS calculation algorithm.
Introduced with CSS3 and now an indispensable part of all modern projects, the box-sizing: border-box; command gives the browser this critical instruction:
"The width value I provide is the TOTAL outer boundary of the box; no matter what I add inside, never exceed this limit."
How It Works: The "Inclusion" Logic instead of "Addition"In this model, when you set width: 200px; the box occupies exactly 200 pixels of space on the screen, down to the last millimeter.
So, what happens if we subsequently add 20px of padding to this box? While the box would swell outward in the default model, the browser acts intelligently in the border-box model and narrows the Content area instead.
It creates the necessary space for padding and borders by "borrowing" it from the internal text area without changing the total width of the box.
Example Scenario: 200px Width + 20px Padding + 5px Border.
Result: The box still remains exactly 200px in total, and the browser automatically reduces the content area to 150 pixels ( 200 - 40 - 10 = 150 ).
Advantage: Flawless LayoutsThe greatest advantage of this model is "Predictability."
For example: Imagine you give two boxes a 50% width to split the screen in half.
content-box (Legacy): If you add a border, it becomes 50% + 50% + Borders, and because the total exceeds 100%, the boxes will no longer fit side-by-side; the design breaks.
border-box (Modern): No matter how much border or padding you add, the boxes stay fixed at the 50% limit and align perfectly side-by-side.
Important Exception: MarginThe only exception you must remember here is the concept of Margin ( External Spacing ).
Regardless of which model ( border-box or content-box ) you use, Margin is always excluded from the calculation.
This is because Margin does not belong to the box itself, but to the space outside the box. While it does not affect the total size, it continues to expand the box's area of influence (footprint).
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Box Model and Pitfall Example</title>
<link rel="stylesheet" href="style.css?v=1.0.150">
</head>
<body>
<div class="wrapper">
<h2>1. Pitfall Model (Content-Box)</h2>
<div class="kutu tuzak-model">
Width: 300px is set.<br>
But on screen I occupy <strong>360px</strong>.<br>
<small>(Padding and border overflow outward)</small>
</div>
</div>
<br><br>
<div class="wrapper">
<h2>2. Modern Model (Border-Box)</h2>
<div class="kutu modern-model">
Width: 300px is set.<br>
On screen I occupy exactly <strong>300px</strong>.<br>
<small>(Padding and border are included inside)</small>
</div>
</div>
</body>
</html>
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
padding: 20px;
}
h2 {
color: #333;
border-bottom: 2px solid #333;
padding-bottom: 10px;
}
/* COMMON BOX STYLES */
.kutu {
background-color: #3498db;
/* Blue Background (Content) */
color: white;
font-size: 18px;
margin-bottom: 40px;
/* Outer spacing (Margin) */
/* Mathematical Values */
width: 300px;
/* Target Width */
padding: 20px;
/* Inner Spacing */
border: 10px solid #2c3e50;
/* Border */
}
/* SCENARIO 1: PITFALL (Default Behavior) */
.tuzak-model {
box-sizing: content-box;
/* This is the default, even if not written */
/* CALCULATION:
Width (300) + Padding (20+20) + Border (10+10)
TOTAL WIDTH = 360px (Larger than expected!)
*/
}
/* SCENARIO 2: SOLUTION (Modern Approach) */
.modern-model {
box-sizing: border-box;
/* Magic Code */
background-color: #27ae60;
/* Green (for distinction) */
/* CALCULATION:
Width (300) -> This is the total width.
The browser includes padding and border inside this 300.
TOTAL WIDTH = 300px (Exactly as intended)
*/
}
/* VISUAL HELPER (Imaginary line to show margin) */
.wrapper {
border: 1px dashed red;
/* To visualize how far margin pushes */
display: inline-block;
}