Introduction
The box model controls how elements take up space on a webpage. Understanding common issues helps you fix layout problems easily.
Jump into concepts and practice - no test required
/* Box model properties example */ .element { width: 200px; padding: 20px; border: 5px solid black; box-sizing: content-box; /* or border-box */ }
box-sizing is content-box, which excludes padding and border from width and height..box1 { width: 200px; padding: 20px; border: 5px solid black; box-sizing: content-box; }
.box2 { width: 200px; padding: 20px; border: 5px solid black; box-sizing: border-box; }
.box3 { width: 100%; padding: 10px; box-sizing: border-box; }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>Box Model Issues Example</title> <style> .container { width: 200px; background-color: #f0f0f0; margin-bottom: 1rem; } .content-box { width: 200px; padding: 20px; border: 5px solid #333; box-sizing: content-box; background-color: #cce5ff; } .border-box { width: 200px; padding: 20px; border: 5px solid #333; box-sizing: border-box; background-color: #d4edda; } </style> </head> <body> <section class="container"> <h2>Content-box (default)</h2> <div class="content-box">Box with content-box sizing</div> </section> <section class="container"> <h2>Border-box</h2> <div class="border-box">Box with border-box sizing</div> </section> </body> </html>
box-sizing: border-box; is a common way to avoid unexpected size issues.content-box, so plan your widths carefully.box-sizing changes how width and height are calculated.border-box often prevents layout problems caused by padding and borders.box-sizing changes whether width/height include padding and border or not.box-sizing -> Option Bcontent-box excludes padding and border; border-box includes them.box-sizing and the value to include padding and border is border-box.div {
width: 200px;
padding: 20px;
border: 5px solid black;
box-sizing: content-box;
}
What will be the total width of the div element as seen in the browser?content-box, width is only content width; padding and border add outside it.p {
width: 300px;
padding: 10px;
border: 2px solid blue;
box-sizing: border-box;
}
But the paragraph still overflows its container. What is the most likely cause?border-box includes padding and border inside the width, so width 300px is total size.border-box, width includes padding and border, so width: 400px means total size is 400px.