問題描述
我的網站上有一個固定的導航欄,它位于頂部,帶有可將我帶到頁面下方不同部分的鏈接.但是,因為我的固定導航欄的高度為 40px,所以每個部分的開頭 40px 都被覆蓋了.我將如何使用 HTML 或 CSS 將我的鏈接帶我的位置偏移 40 像素?謝謝.
I have a fixed navigation bar on my website that stays at the top with links that take me to different sections further down the page. However, because my fixed nav bar has a height of 40px, the beginning 40px of every section is covered up. How would I offset where my links take me by 40px using either HTML or CSS? Thanks.
推薦答案
您可以嘗試將虛擬"錨點絕對定位在每個部分頂部上方 40 像素處.您可以給它們零寬度/高度和隱藏可見性,以確保這些錨點不會影響頁面的顯示方式.當用戶單擊固定導航欄中的鏈接之一時,窗口將滾動到虛擬錨點的頂部,在其實際部分的開頭上方 40 像素處.
You might try absolutely positioning "dummy" anchors 40 pixels above the top of each section. You can give them zero width/height and hidden visibility to ensure that these anchors don't affect how your page is displayed. When the user clicks one of the links in your fixed navigation bar, the window will scroll to the top of the dummy anchor, 40 pixels above the beginning of its actual section.
示例 HTML:
<div class="navbar">
<a href="#anchor1">Anchor 1</a>
<a href="#anchor2">Anchor 2</a>
<a href="#anchor3">Anchor 3</a>
</div>
<div class="section">
<span id="anchor1" class="anchor"></span>
Section Content
</div>
<div class="section">
<span id="anchor2" class="anchor"></span>
Section Content
</div>
<div class="section">
<span id="anchor3" class="anchor"></span>
Section Content
</div>?
示例 CSS:
body {
padding-top: 40px;
}
.navbar {
position: fixed;
width: 100%;
height: 40px;
top: 0;
left: 0;
z-index: 10;
border-bottom: 1px solid #ccc;
background: #eee;
}
.section {
position: relative;
}
.anchor {
display: block;
position: absolute;
width: 0;
height: 0;
z-index: -1;
top: -40px;
left: 0;
visibility: hidden;
}
有關工作示例,請參閱 http://jsfiddle.net/HV7QL/
For a working example, see http://jsfiddle.net/HV7QL/
CSS3 還包括 :target
偽類,它適用于 id
已被 引用的元素>href
文檔中的鏈接,或 URL 的哈希值.您可以在 :target
的頂部應用 40 像素的填充,該填充將僅應用于用戶從固定導航欄中選擇的部分.
CSS3 also includes the :target
pseudo-class, which applies to an element whose id
has been referenced by the href
of a link in the document, or the hash value of the URL. You can apply a 40-pixel padding to the top of the :target
that will be applied only to the section the user selects from the fixed navbar.
示例 CSS:
.section:target {
padding-top: 40px;
}
這在語義上比上述方法更清晰,但不適用于舊版瀏覽器.
This is semantically cleaner than the method described above, but won't work on older browsers.
工作示例:http://jsfiddle.net/5Ngft/
這篇關于如何抵消固定導航欄將我帶到的位置?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!