Why does a nested HTML element make my CSS jump?

Here is the puzzle. Main page, one element:

http://jsfiddle.net/PZj6t/

HTML:

<div id="container"></div>โ€‹ 

CSS

 body, html { height: 100%; margin: 0; padding: 0; background-color: black; } #container { position: relative; margin: 0 auto; width: 400px; height: 100%; background-color: #666; }โ€‹ 

It looks the way I want it, with a C # container, gently flush to the top. But when I add a nested element:

http://jsfiddle.net/PZj6t/1/

HTML:

 <div id="container"> <nav id="topnav"></nav> </div>โ€‹ 

CSS (new):

 #topnav { width: 100%; height: 40px; margin: 30px 0; background-color: red; }โ€‹ 

The container is dumped. It seems that the margin-top from #topnav is somehow being passed to the container, and now there is a scroll bar on the page that I don't want. (I am testing in Chrome.) How can I prevent this?

(As an added secret, if I add border: 1px solid white; in #container CSS, the jump will disappear. This will be fine, except that it also adds unwanted two-pixel scrolls to the page.)

+4
source share
4 answers

This is due to a feature of CSS called crash. If there is no indentation or border on the parent element, the parent element and its child fields are "collapsed" to a larger value of two and essentially apply to the parent.

In your situation, I would suggest simply adding an additional inner shell to the container and throwing some addition on it to simulate the effect of the margin you are looking for: http://jsfiddle.net/PZj6t/3/

Everything that is inside the #inner div or lower should behave as you expect, since the fields only collapse when they are on the edge of their parent (and there are no extras or borders).

+4
source
 display:inline-block; 

This will be fixed in the navigation item that appears. To do this with a short break, see here for more details.

+1
source

Jblasco is correct, but this is a tidier solution: http://jsfiddle.net/PZj6t/4/

 #container { position: relative; margin: -1px auto 0; width: 400px; height: 100%; padding-top:1px; background-color: #666; } #topnav { width: 100%; height: 40px; margin: 29px 0 30px; background-color: red; } 
+1
source
 #container { margin: 0 auto; width: 400px; height: 100%; background-color: #666; border:1px solid; } 

http://jsfiddle.net/PZj6t/12/

 Update: 

http://jsfiddle.net/PZj6t/1/
apply display:inline-block; to both container and topnav

0
source

Source: https://habr.com/ru/post/1399210/


All Articles