DEV Community

Cover image for THE BOX MODEL AND BOX-SIZING.
Peter Mungai
Peter Mungai

Posted on

THE BOX MODEL AND BOX-SIZING.

The box-model and box-sizing are css elements that needs to be used together in many occasions if not all.

Lets dive on what they are:

-The box model is used for design and layouts that wraps around every html element.

The box-model consist of the content, padding, border and margin as seen below.

The box model

The content area contains the content of the the box.

Padding adds more background around the content.

Border creates a visible border around the content and its padding.

Margin creates more background outside the border.

example in code

.content {
background-color: aqua;
padding: 2em;
border: 2px solid red;
margin: 2em;
}
Enter fullscreen mode Exit fullscreen mode

One properties that is important to note when using the box model is width.
The width sets the width of the content area only.
This means when adding some units in padding and border they are not accounted for-they are added on top of the width of the content.

i.e if width is 200px and padding-left and padding-right are 10px and the border is 5px the resulting width will be 230px.

N/B: Margin is not included when calculating the width since it is outside the border.The primary use of margin is to separate elements.

This is where the box-sizing can be useful.
When we declare

* {
box-sizing: border-box;
}
Enter fullscreen mode Exit fullscreen mode

The width accounts for the padding and the border which allows us to get the intended width we wanted.

MORE WIDTH TIPS

The default width value is auto which lets the browsers to control the width of the elements.

But it can be tricky when we set the width to 100% since this results to overflows issues.
When we declare a width of 100% and add border and margin the content starts to overflow.This is because the content is set to 100% and takes all the space making the addition of border and margin make it to overflow.

.content {
width: 100%;
background-color: aqua;
padding: 2em;
border: 2px solid red;
margin: 2em;
}
Enter fullscreen mode Exit fullscreen mode

Using the box-sizing helps a bit in this scenario-it includes the padding and border in it but the remedy is to leave the width to default-auto.

* { box-sixing: border-box;}

.content {
background-color: aqua;
padding: 2em;
border: 2px solid limegreen;
margin: 2em;
}
Enter fullscreen mode Exit fullscreen mode

Thanks for reading this far I hope you enjoyed.

Top comments (0)