How to keep a fixed div position in accordance with a centered div?

Not sure how to make amends. I have such an html structure:

<div id="nav"></div> <div id="wrapper"> <div id="content"> </div> </div> 

With some css like this:

 #nav { width: 200px; height: 50px; margin: 0 0 0 -100px; position: fixed; left: 50%; background: red; } #wrapper { width: 250px; height: 1000px; margin: 0 auto; background: blue; } #content { width: 200px; height: 1000px; margin: 0 auto; background: green; } 

The wrapper is wider than the content, and the content is concentrated in the shell. My problem is to keep the div div that is attached to the top of the page centered / aligned with the contents of the div when the window is smaller than the wrapper of the div. Problems arise when scrolling left and right, a fixed div remains centered in the window, and the contents of the div scroll left and right. I am trying to execute this without javascript.

Here, the jsfiddle of what I run resizes the results window to see how the nav div will not center / align with the contents of the div when the window is smaller than the wrapper of the div.

http://jsfiddle.net/p2Mzx/1/

Thanks in advance!

+6
source share
4 answers

The easiest solution is to place #nav in your #wrapper and give it a horizontal size of 25px:

HTML:

 <div id="wrapper"> <div id="nav"></div> <div id="content"> </div> </div> 

CSS

 #nav { width: 200px; height: 50px; margin: 0 25px; position: fixed; top: 0; background: red; } #wrapper { width: 250px; height: 1000px; margin: 0 auto; background: blue; } #content { width: 200px; height: 1000px; margin: 0 auto; background: green; } 

Also see fiddle .

+5
source

I think you can add margin: 0 auto for navigation too.

Then nav will be placed in the parent just like for the wrapper. but removed fixed form nav. position:fixed makes it positioned for the browser window and from the narmal stream. Do you want this?

0
source

It would be more appropriate to place the navigator inside the shell, just above the contents.

 <div id="wrapper"> <div id="nav"></div> <div id="content"></div> </div> 

CSS navigator can have left and right margins 25px. Absolute positioning and width are also not required.

 #nav { height: 50px; margin: 0px 25px 0px 25px; background: red; } #wrapper { width: 250px; height: 1000px; margin: 0 auto; background: blue; } #content { width: 200px; height: 1000px; margin: 0 auto; background: green; }​ 

See this script: http://jsfiddle.net/p2Mzx/20/

0
source

You can capture navigation and content to give a padding-top .

Consider this jsfiddle link

0
source

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


All Articles