The box model helps you understand how the size of elements on a webpage is calculated. It shows how content, padding, borders, and margins add up to the total space an element takes.
Box model calculation in CSS
Total width = content width + left padding + right padding + left border + right border + left margin + right margin Total height = content height + top padding + bottom padding + top border + bottom border + top margin + bottom margin
The content is the actual area where text or images appear.
Padding adds space inside the box, around the content.
content width: 200px padding: 10px border: 5px solid margin: 20px Total width = 200 + 10 + 10 + 5 + 5 + 20 + 20 = 270px
content height: 100px padding-top: 15px padding-bottom: 15px border-top: 2px solid border-bottom: 2px solid margin-top: 10px margin-bottom: 10px Total height = 100 + 15 + 15 + 2 + 2 + 10 + 10 = 154px
This example shows a blue box with specific content width and height. Padding, border, and margin add space around it. The box-sizing: content-box; means the width and height apply only to the content area.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Box Model Calculation Example</title> <style> .box { width: 200px; height: 100px; padding: 20px; border: 5px solid #333; margin: 15px; background-color: #a0c4ff; box-sizing: content-box; } </style> </head> <body> <main> <section> <article> <div class="box" aria-label="Blue box showing box model example"> This box has content width 200px, padding 20px, border 5px, and margin 15px. </div> </article> </section> </main> </body> </html>
Remember, box-sizing: content-box; means width and height only count the content area.
If you use box-sizing: border-box;, padding and border are included inside the width and height.
Margins do not affect the size of the box but add space outside it.
The box model adds content, padding, border, and margin to calculate total element size.
Padding adds space inside the box; margin adds space outside.
Understanding this helps you control layout and spacing on your webpage.