Standard CSS box model

Can anyone tell why we need to add two times padding and two times border for getting the width of the box?

.box {
width: 350px;
height: 150px;
margin: 10px;
padding: 25px;
border: 5px solid black;
}

The space taken up by the box will be 410px wide (350 + 25 + 25 + 5 + 5) and 210px high (150 + 25 + 25 + 5 + 5).

in the above why are adding padding value of 25 two times and border value of 5 two times instead of adding one time to get the width and height of the box

Hi @mungara_hitesh and welcome to the community :wave:

When we use padding with only one value, it means that we have this padding on all four sides (top, bottom, left, right). It’s the same for margin and border.
350 + 25 + 25 + 5 + 5 :arrow_right: 350 width + 25 left padding + 25 right padding + 5 left border + 5 right border.

I hope that helps! :slightly_smiling_face:

Have a nice day,
Michael

1 Like

Thanks for the reply :slight_smile:

So, you are saying we only have to add the padding value of left and right to width?

Then why aren’t adding the padding values of padding-top and padding-bottom to the width

1 Like

The paddings on the top and bottom are irrelevant for the width. They are only needed to calculate the height.

As padding:25; means that padding values of top, bottom, right, left is 25, we will be adding the padding values of left and right to the width and we will be adding the padding values of top and bottom to the height? Is it correct?

1 Like

Yes, exactly. You got it! :+1:

Thanks! Have a nice day :smile:

1 Like

Hi mungara
I am also learning CSS so when I saw your query I created a box 350px X 150 px and inspected it in a browser.


As you can see the green area in the center 350 X 150.

Then applied padding and margin dimension to the same box and got this


From what I see, please correct me if I am wrong:
it seems the padding and border length is deducted from the box’s original dimension (350 -25-25-5-5=290) (150-25-25-5-5=90) and margin is placed outside the box.

1 Like

Hi @Deepak_Tandan and thanks for the screenshots!

What we looked at above was that standard box model. This is how browsers work by default: Adding padding and border to the width to build the total size.
Since people found out that this can lead to problems, an alternative box model was created. Width is the total size and padding and border are subtracted. This is what we see in your screenshots and is described here:

Because this alternative box model is much better nearly every website today uses it by putting something like this at the start of their CSS:

html {
  box-sizing: border-box;
}
*, *::before, *::after {
  box-sizing: inherit;
}

This will change the box model on all elements to the newer box model you described in your post @Deepak_Tandan.

Have a nice day,
Michael