2011-11-27 101 views
4

頁面內的鏈接將您的內容滾動到瀏覽器窗口的頂部。有什麼辦法可以爲此添加保證金嗎?我將使用一些JavaScript來指導滾動,但希望有一個可行的後備。添加頁面內鏈接的邊距

因此,簡而言之,我可以在CSS中添加一個邊距,它將在瀏覽器窗口的頂部和頁面鏈接的一部分之間添加一些空間。

HTML:

<nav> 
    <a href="#test">TEST</a> 
</nav> 
<div class="section"> 
    <a name="test"></a> 
    <p>This content should be offset from the top of the page when scrolled to</p> 
</div> 

回答

5

頁首鏈接的首選方式是使用id而不是name屬性。

<a href="#test"> 

應該匹配了:

<div id="test"> 

從這裏你可以輕鬆地添加填充到#TEST div的頂部,這將是你的滾動位置。

例如:http://tinkerbin.com/EvV7byy9

+0

謝謝!將接受盡快 – technopeasant

+0

tinkerbin.com不再;也許這個鏈接可以被重寫到http://tinkerbin.heroku.com/,但它似乎也不能很好地工作。 – Arjan

0

嗯,我將設置錨在每個部分進行絕對定位,約10px的從節開始了。它看起來像這樣:

.section { 
    position: relative; 
} 

.section > a { 
    position: absolute; 
    top: 10px; 
} 

這基本上是一個10像素的邊距。您可以相應地調整頂部的值以更改邊距/填充。我還使用了直接後代操作符(>),因此段落中的鏈接不會受到影響。

另外,如@NathanManousos所述,您不應再使用name屬性,而是使用ID屬性。相關文檔鏈接將滾動到任何元素的ID,而不僅僅是鏈接。您可以在每個分區DIV上放置一個ID,並使用填充值滾動到div的頂部,填充將導致實際內容在div中進一步下降。

<style> 
    .section { 
     padding-top: 10px; 
    } 
</style> 

... 

<nav> 
    <a href="#test">TEST</a> 
</nav> 
<div class="section" id="test"> 
    <p>This content should be offset from the top of the page when scrolled to</p> 
</div>