Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You don't need to even use JQuery for this.</p> <p><a href="http://jsfiddle.net/24ba7/3/" rel="nofollow noreferrer">You just need CSS (click for live example):</a></p> <pre><code> #header { position:fixed; width:900px; height:100px; left: 50%; margin-left: -450px; } </code></pre> <p><a href="http://jsfiddle.net/24ba7/3/embedded/result/" rel="nofollow noreferrer">Fullscreen version.</a></p> <p>To explain this a bit, the negative margin is half of the width that you defined, because elements center on the page based on their top-left most point, so we compensate for that by moving it back half of the way.</p> <p>Fixed positioning defaults to being aligned to as far left and as far top as it will go, so <a href="https://stackoverflow.com/questions/2005954/center-element-with-positionfixed">centering a fixed element</a> requires a little massaging.</p> <p>But as you see this is a CSS solution, so unless you need to use JQuery, I would avoid it. It adds unnecessary overhead and complexity for something that can be done in pure CSS.</p> <hr/> <p><strong>JQUERY SOLUTION</strong></p> <p><a href="http://jsfiddle.net/24ba7/7/" rel="nofollow noreferrer">http://jsfiddle.net/24ba7/7/</a></p> <pre><code> if ($(window).scrollTop() &gt; HeaderTop) { $('#header').css({ position: 'fixed', top: '0px', left:'50%', marginLeft: '-450px' }); </code></pre> <p>You can't use <code>auto</code> <code>margin</code> with <code>fixed</code> positioning, you need to use the margin fix that I suggested.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload