2
votes

Actually I have confusion as I read two different things on these websites. I know about the box-sizing and how it effects box model, but what if we are not considering the sizing and want to tell the size of element. Refer the url's below:

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

The total width of an element should be calculated like this:

Total element width = width + left padding + right padding + left border + right border + left margin + right margin

The total height of an element should be calculated like this:

Total element height = height + top padding + bottom padding + top border + bottom border + top margin + bottom margin

https://css-tricks.com/the-css-box-model/

The size of the box itself is calculated like this:

Width= width + padding-left + padding-right + border-left + border-right Height= height + padding-top + padding-bottom + border-top + border-bottom

I think from my understanding we calculate width = width + padding + border as total width of an element in default box-sizing.

1
This is a much more credible resource: developer.mozilla.org/en/docs/Web/CSS/box-sizing - also, content-box (does not include padding, border or margin) is different to border-box (does not include margin but includes padding and border) but they are both the box model so your question is too general reallyStudioTime
The box-sizing property is used to alter the default CSS box model used to calculate width and height of the elements. what if I dont want to alter it.gaurav rathor

1 Answers

0
votes

Here's what I've roughly observed in Chrome.

If you set * {box-sizing: border-box;}, then an element's width equals width + border + padding. The width value is equivalent to width showed in devtool.

An element's width (of course) include its children's margin, but doesn't include its own margin. The width value is also equivalent to width showed in devtool. But you need to care about margin collapsing when calculating.

However, if for exmaple the topmost element's margin-top collapses, rendering out of body, then the extra magin doesn't add to the element height of the box showed in the devtool. But you can use document.getElementsByTagName('html')[0].scrollHeight to get the whole height.

So back to your question:

Do we include margin in css box model while determining width or height of a element?

I would say mostly Yes.

Again, with boder-box, an element's width == content-width(include margin of element's children) + border + padding.