What is it with a box? Reserve margin affecting parents

HTML and CSS sometimes scare my mind.

A div with a border shows the background color for the entire height of the element and its contents. Why is it without a border, the DIV will consider (to inherit the reverse?) Its child fields?

As an example, here's a JSFiddle illustrating behavior with and without borders.

http://jsfiddle.net/ahNUX

http://jsfiddle.net/ahNUX/1/

Does anyone want to explain how this is a β€œfunction” and not some kind of mistake?

Update: Adding 1px indentation to the parent is a quick fix.

+7
source share
2 answers

Of course. In CSS, by default, adjacent top and bottom margins overlap. This was a reasonable workaround before the adjacent selector ( + ) was counted / supported, as it meant that if you wrote h2 {margin-top: 3em;} , you should have 3 places at a distance above your h2s, even if there was a paragraph in front of him with a lower limit of 1m.

In your second example, since the <div> has no top or bottom padding or borders, its top and bottom fields are adjacent to the top and bottom fields by default <h1> . Despite the fact that the <div> s fields have no height, theyre still treated as if they existed, and therefore the <h1> s fields should overlap them. Since the <div> fields are by definition outside the background color <div> , the <h1> s fields must also be located outside.

In the first example, since the <div> has a border, its fields no longer adjoin the <h1> s fields, so there is no overlap. You can get the same effect by adding the top and bottom additions to the <div> : http://jsfiddle.net/ahNUX/7/

(I'm not sure that you mean <div> "reverse inheritance" of its child additions. In your examples, neither <div> nor <h1> have uppercase letters. The space inside the <div> in the first example is created by the upper and lower fields <h1> .)

+8
source

This is the result of dropping fields. See http://www.w3.org/TR/CSS2/box.html#collapsing-margins

In a nutshell, the upper and lower fields in the <h1> element in your example may crash (or match) the field with another element that is above or below it, which will lead to a conflict with the background color, so it is not shown. On the other hand, if you have a border, the rules change.

The spectrum explains this quite well, albeit in a dry and technical tone.

+7
source

All Articles