[CSS] Box Model

[CSS] Box Model

Introduction

This article will introduce the CSS box model, which we can use when designing the website layout.

Every HTML element, such as <div> is wrapped around the box, which consists of padding, border and margin.


Box Model - Padding, Border, Margin

As said earlier, the box model consists of padding, border, margin and content. Content is basically where the content of an element goes in.

Content

  • The content of the box, where text and images appear.

Padding

  • Clears an area around the content.

  • The padding is transparent.

Border

  • A border that goes around the padding and content.

Margin

  • Clears an area outside the border.

  • The margin is transparent


Example

CSS:

.box1 {
    padding: 10px;
    border: 10px solid green;
    margin: 10px;
}

.box2 {
    padding: 5px;
    border: 5px solid red;
    margin: 5px;
}

HTML:

<div class="box1">
    <div class="box2">CSS box model</div>
</div>

Result:


Playing with Box Model

To help you to better understand the box model, open the developer tool on the Chrome browser by pressing F12. Then, go to elements.

Internet browsers provide you with the box model for each HTML element. Simply just select the HTML element you want, then put your mouse cursor on the box model. It will highlight the part you have chosen.


Box-Sizing

box-sizing CSS property sets how the total width and height of an element is calculated. If you were to give a width of 200px on a certain element, the width is only applied to the content box.

For example:

div {
    width: 400px;
    border: 5px dashed black;
    margin: 10px;
    padding: 30px;
    background-color: lightgreen;
}
<body>
    <div>Some content</div>
</body>

The total width of this box model is 470 px because...

400px + (30px  2) + (5px * 2) = 470px

As I said before, the width is only applicable to the content box, which makes us confusing. We would have to calculate the total width every time.

To solve this problem, we can use box-sizing CSS property.

div {
    width: 400px;
    border: 5px dashed black;
    margin: 10px;
    padding: 30px;
    background-color: lightgreen;
    box-sizing: border-box; /* new!!! */
}

The total width is now 400px, which includes the border and padding. With this, it is much easier to work on the design and layout of a web page.


Reference

https://www.w3schools.com/css/css_boxmodel.asp

https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/The_box_model

Did you find this article valuable?

Support Jay's Dev Blog by becoming a sponsor. Any amount is appreciated!