偏移固定标题的锚点部分

时间:2014-03-09 01:27:35

标签: html css

我已经看到了其他答案,但它们似乎都不适合我。

我想要的是:当我输入网址.../page.html#two以转到#two,但距离页面顶部偏移50px时。

注意:我添加了big space<a>'s,因为您无法在jsfiddle中输入网址。我希望它可以与网址一起使用,也可以使用链接。

<body>
    <section id="one">First section</section>
    <section id="two">Second section</section>
    <section id="three">Third section</section>
    <div id="big_space"></div>
    <a href="#one">one</a>
    <a href="#two">two</a>
    <a href="#three">three</a>
</body>

body
{
    height: 2000px;
}

#big_space
{
    height: 1000px;
}

section
{
    height: 100px;
    background-color: lightblue;
    margin-bottom: 5px;
}

这是JSfiddle的链接:http://jsfiddle.net/hAmCL/

我尝试使用section:before,但它似乎给出了错误的结果(我已经在jsfiddle中对其进行了评论)

1 个答案:

答案 0 :(得分:2)

这不可能像你想要的那样使用纯CSS,尽管有一些半工作

此方法仅适用于某些情况,但诀窍是使用margin-top:-50px; padding-top:50px;。这使得元素显示在相同的位置,除了背景将50px更高并向上推50px。该方法的Here's a demo

我推荐的第二种方法是涉及添加内部元素的方法。我决定格式化每个<section id="one"><div class="reference" id="refOne"></div>First section</section>。然后你可以指向链接中的refence,即<a href="#oneRef">one</a>。然后它只需要以下简单的CSS

section {
    ... Your other lines ...
    position:relative;
}
.reference {
    position:absolute;
    top:-50px;
}

Demo。这种方法将所有元素保留在性能和外观之前,但需要稍微额外的HTML标记

能够像你想要的那样引用元素的pseuo元素会很高兴,但是我理解这样做是非语法正确的

相关问题