saiprasad padhy
Sai Prasad

Follow

Sai Prasad

Follow
CSS layout made easy using box-sizing

CSS layout made easy using box-sizing

In this article, We will explore how box-sizing works and its implementation of it in order to make CSS layout easy and avoid strange issues.

saiprasad padhy's photo
saiprasad padhy
ยทDec 3, 2022ยท

2 min read

Most of the time, CSS behaves strangely mainly when calculating an element's height and width. As we already know CSS uses box-model which is a box that wraps around every element in the HTML. it consists of margin, padding, border and content of the element.

When we are calculating an element's height or width, it means the sum of the margin, padding, border and content.

CSS box model

Let's take a simple example and understand how box-sizing works. I'm taking 2 divs and assigning height and weight as 300px and padding-top and padding-bottom of 50px to the first div. The second div will only have height and width to see the difference.

.box--1{
  height: 300px;
  width: 300px;
  background-color: red;
  padding-top: 50px;
  padding-bottom: 50px
}
.box--2{
  height: 300px;
  width: 300px;
  background-color: green;
}

The output will look like below, here padding-top and bottom increased the total height of the red div. that means the total height of the div is 300px + 50px + 50px

Now, Will add box-sizing: border-box and let's see the changes.

.box--3{
  box-sizing: border-box;
  height: 300px;
  width: 300px;
  background-color: red;
  padding-top: 50px;
  padding-bottom: 50px
}
.box--4{
  height: 300px;
  width: 300px;
  background-color: green;
}

let's see the output of the above code, here box height remains the same even though after adding padding-top and bottom.

border-box tells the browser to account for any border and padding in the values you specify for an element's width and height. In the above example, we set element's width to 300 pixels, that 300 pixels will include any border or padding you added, and the content box will shrink to absorb that extra width. This typically makes it much easier to size elements.


Thanks for reading this article, I hope this blogs helps in understanding box-sizing proprty in CSS. Please share with your friends and community, it motivates me to write more awesome blogposts.

See you in my next blogpost.

ย 
Share this