我正在努力清理我的锚的工作方式。我有一个固定在页面顶部的标题,所以当你链接到页面其他地方的锚时,页面跳转,锚位于页面顶部,留下固定标题后面的内容(我希望这是有意义的)。我需要一种方法来抵消锚的25px从头部的高度。我更喜欢HTML或CSS,但Javascript也可以接受。


当前回答

@AlexanderSavin的解决方案在WebKit浏览器中对我来说很棒。

另外,我不得不使用:target伪类,它将样式应用到选定的锚来调整FF, Opera和IE9中的填充:

a:target {
  padding-top: 40px
}

注意,这种风格不适合Chrome / Safari,所以你可能不得不使用css-hacks,条件注释等。

我还想注意到,Alexander的解决方案工作,因为目标元素是内联的。如果你不想要链接,你可以简单地改变显示属性:

<div id="myanchor" style="display: inline">
   <h1 style="padding-top: 40px; margin-top: -40px;">My anchor</h1>
</div>

其他回答

我在每个h1元素之前添加了40px-height .vspace元素。

<div class="vspace" id="gherkin"></div>
<div class="page-header">
  <h1>Gherkin</h1>
</div>

CSS中:

.vspace { height: 40px;}

它工作得很好,空间也没有堵塞。

@AlexanderSavin的解决方案在WebKit浏览器中对我来说很棒。

另外,我不得不使用:target伪类,它将样式应用到选定的锚来调整FF, Opera和IE9中的填充:

a:target {
  padding-top: 40px
}

注意,这种风格不适合Chrome / Safari,所以你可能不得不使用css-hacks,条件注释等。

我还想注意到,Alexander的解决方案工作,因为目标元素是内联的。如果你不想要链接,你可以简单地改变显示属性:

<div id="myanchor" style="display: inline">
   <h1 style="padding-top: 40px; margin-top: -40px;">My anchor</h1>
</div>

从这个链接中给出的答案中借用一些代码(没有指定作者),你可以包括一个很好的平滑滚动效果到锚,同时让它停在锚上方的-60px处,很好地适合固定引导导航条的下方(需要jQuery):

$(".dropdown-menu a[href^='#']").on('click', function(e) {
   // prevent default anchor click behavior
   e.preventDefault();

   // animate
   $('html, body').animate({
       scrollTop: $(this.hash).offset().top - 60
     }, 300, function(){
     });
});

对于现代浏览器,只需将CSS3:target选择器添加到页面。这将自动应用于所有的锚。

:target {
    display: block;    
    position: relative;     
    top: -100px;
    visibility: hidden;
}

你可以使用a[name]:not([href]) css选择器在没有ID的情况下实现这一点。这仅仅是查找有名称且没有href的链接,例如<a name="anc1"></a>

一个示例规则可能是:

a[name]:not([href]){
    display: block;    
    position: relative;     
    top: -100px;
    visibility: hidden;
}