Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

css border changes the div size completely? [duplicate]

Tags:

html

css

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: div without the border - see the relatively small background and now look at this photo (the only difference is the border...) div with border, suddenly the background is much bigger!

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.

like image 279
JimmyBoy Avatar asked Jun 16 '15 20:06

JimmyBoy


People also ask

How do I keep the border from changing size in CSS?

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.

How do you avoid double border in CSS?

Add a border-left and border-top to the parent. Add border-right and border-bottom to each of the children.

How do I make a div stay the same size?

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.

Does border Add to width CSS?

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.


1 Answers

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.

like image 186
Guffa Avatar answered Jan 03 '23 11:01

Guffa