2013-07-08 108 views
0

我有jQuery的問題固定的頭,我做了一個固定的頭,但,當它向下滾動它不是水平對齊。在CSS中,我把margin-left:auto; margin-right:auto;它做對了,但是當我向下滾動標題是去左側。CSS,jQuery的水平對齊

我不知道,如果是的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:

<header> 
    <img src="darkness.png" height="100" /> 
    </header> 
    <div id="header"> 
    <ul> 
    <li>Home</li><li>About</li> 
    </ul> 
    </div> 
    <div class="content"> 
    </div> 

的jsfiddle演示:http://jsfiddle.net/24ba7

+2

這裏是代碼的的jsfiddle:http://jsfiddle.net/24ba7/ – Johannes

回答

1

你甚至不需要爲此使用JQuery。

You just need CSS (click for live example):

#header { 
     position:fixed; 
     width:900px; 
     height:100px; 
     left: 50%; 
     margin-left: -450px; 
    } 

Fullscreen version.

爲了解釋這一點,負利潤率是你定義的寬度的一半,因爲根據他們的上方最左邊的點頁面上的元素中心,所以我們通過將其移回一半來彌補這一點。

固定的位置默認爲對齊到最左邊和最遠,因此centering a fixed element需要一點點按摩。

但是,正如你看到的這是一個CSS解決方案,所以除非你需要使用JQuery,否則我會避免它。它增加了不必要的開銷和複雜性,可以在純CSS中完成。


JQUERY SOLUTION

http://jsfiddle.net/24ba7/7/

if ($(window).scrollTop() > HeaderTop) { 
     $('#header').css({ 
      position: 'fixed', 
      top: '0px', 
      left:'50%', 
      marginLeft: '-450px' 
     }); 

不能使用automarginfixed定位,您需要使用保證金修復,我建議。

+0

我不希望類似的東西,我希望有一個固定的頭時,我向下滾動頁面,類似的東西:[JSFiddle](http://jsfiddle.net/r8CWD/embedded/result/)。但標題將在左側 – Darkness

+0

檢查我的編輯。這應該解決它。 – Johannes

+1

是的,這解決了我的問題,非常感謝。謝謝!!! – Darkness

0

你可以添加一個額外的div像這樣

<div id="wrapp"> 
    <div id="header"> 
     <ul> 
      <li>Home</li> 
      <li>About</li> 
     </ul> 
    </div> 
</div>  

這個CSS

#wrapp{ 
    width:100%; 
    position:fixed; 
    top:0px; 
}  

所以你可以有保證金:0汽車;工作
http://jsfiddle.net/24ba7/6/

+0

謝謝,但這不是我想要的。非常感謝。 – Darkness