CSS,jquery水平对齐的固定头
我有一个jquery的问题,我做了一个固定的标题但是,当它向下滚动它没有水平对齐。 在CSS中,我把margin-left:auto; margin-right:auto; 它做得对,但是当我向下滚动标题时,它会向左侧移动。
我不知道jquery或CSS中是否存在问题。
非常感谢。
这是我的jQuery:
$(function () { var HeaderTop = $('#header').offset().top; $(window).scroll(function () { if ($(window).scrollTop() > HeaderTop) { $('#header').css({ position: 'fixed', top: '0px', marginLeft: 'auto', marginRight: 'auto' }); } else { $('#header').css({ position: 'relative', top: '0px' }); } }); });
我的CSS:
html, body { height:100%; } body { margin: 0; padding: 0; } #header { width:900px; height:100px; background-color:#FFF; margin-left:auto; margin-right:auto; border-top:1px; border-top-color:#D2D2D2; border-top-style:solid; border-bottom:1px; border-bottom-color:#D2D2D2; border-bottom-style:solid; } header { background-color:#FFF; width:900px; margin-left:auto; margin-right:auto; text-align:center; } .content { width:900px; margin-left:auto; margin-right:auto; } #header ul { list-style:none; } #header ul li { display:inline; padding:10px; }
我的HTML:
- Home
- About
jsFiddle演示: http : //jsfiddle.net/24ba7
您甚至不需要使用JQuery。
你只需要CSS(点击直播例子):
#header { position:fixed; width:900px; height:100px; left: 50%; margin-left: -450px; }
全屏版。
为了解释这一点,负边距是你定义的宽度的一半,因为元素基于它们的左上角最大点居中在页面上,所以我们通过将其向后移动一半来补偿它。
固定定位默认为尽可能向左和最远对齐,因此固定元素的中心需要一点按摩。
但是正如你所看到的那样,这是一个CSS解决方案,所以除非你需要使用JQuery,否则我会避免使用它。 它为纯CSS中可以完成的事情增加了不必要的开销和复杂性。
JQUERY解决方案
if ($(window).scrollTop() > HeaderTop) { $('#header').css({ position: 'fixed', top: '0px', left:'50%', marginLeft: '-450px' });
您不能使用fixed
定位的auto
margin
,您需要使用我建议的边距修复。
你可以添加一个这样的额外div
- Home
- About
用这个css
#wrapp{ width:100%; position:fixed; top:0px; }
所以你可以有保证金:0自动; 工作的
http://jsfiddle.net/24ba7/6/