我的网站上有一个固定的导航栏,它位于顶部,带有可将我带到页面下方不同部分的链接.但是,因为我的固定导航栏的高度为 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/
这篇关于如何抵消固定导航栏将我带到的位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!