Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep fixed position div aligned with centered div?

Not sure how to title the question. I have an html structure like this:

<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 centered in the wrapper. My problem is keeping the nav div, which is fixed to the top of the page, centered/aligned with the content div when the window is smaller than the wrapper div. Issues arise when you scroll left and right, the fixed div stays centered in the window and the content div scrolls left and right. I'm trying to accomplish this without javascript.

Here's a jsfiddle of what I'm running into, resize the results window to see how the nav div won't stay centered/aligned with the content div when the window is smaller than the wrapper div.

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

Thanks in advance!

like image 412
codybuell Avatar asked Mar 23 '12 02:03

codybuell


1 Answers

The easiest solution would be to put #nav in your #wrapper and give it a horizontal margin 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 the fiddle.

like image 138
jeroen Avatar answered Nov 15 '22 07:11

jeroen