EDIT: found a very good link explaining all about border collapse:
border collapse explained with examples
End of edit. Enjoy :)
I am failing to understand this... Why applying a 1px solid black border to my div changes the div's size by a lot? (without the border I can see a relatively thin line as my back ground color, with the border the רectangle of the background color is much wider, see the pictures) this pic is without applying the border: and now look at this photo (the only difference is the border...)
can someone explain how the border influences so much on the div size / what is really happening here?!
style:
#header {
background-color: yellow;
color: white;
text-align: center;
border: 1px solid black;
}
here is a fiddle so you can play around: my fiddle Thanks a lot, Jimmy.
To avoid the width or height getting increased or decreased when using CSS properties like margin , padding , etc, we can use the CSS property called box-sizing and set its value to border-box on the element in CSS.
Add a border-left and border-top to the parent. Add border-right and border-bottom to each of the children.
if you set width:500px; and height:300px; (or whatever size you want) the div should stay the same size. Also, you can set overflow:hidden; so that if whatever is in the div goes beyond those bounds, it is not shown, and does not resize the div. Save this answer.
By default in the CSS box model, the width and height you assign to an element is applied only to the element's content box. If the element has any border or padding, this is then added to the width and height to arrive at the size of the box that's rendered on the screen.
That's because of margin collapsing.
The margin is not part of the element iself, it's the distance between the element and surrounding elements, or between the element and containing borders or paddings.
In the first image the margins of your header element (a h1
perhaps?) is collapsing outside the div. The margins doesn't affect the size of the div, instead it pushes the surrounding elements away.
When you add a border to the div, then the margins of the header element will push the border away from the header element instead of pushing surrounding elements away. The margins of the header element determine the size of the div.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With