如果我在HTML页面中有一个非滚动头,固定在顶部,有一个定义的高度:
是否有一种方法可以使用URL锚(#fragment部分)让浏览器滚动到页面中的某一点,但仍然尊重固定元素的高度,而不需要JavaScript的帮助?
http://example.com/#bar
WRONG (but the common behavior): CORRECT:
+---------------------------------+ +---------------------------------+
| BAR///////////////////// header | | //////////////////////// header |
+---------------------------------+ +---------------------------------+
| Here is the rest of the Text | | BAR |
| ... | | |
| ... | | Here is the rest of the Text |
| ... | | ... |
+---------------------------------+ +---------------------------------+
我发现处理这个问题的最好方法是(用固定的元素高度替换65px):
div:target {
padding-top: 65px;
margin-top: -65px;
}
如果你不喜欢使用目标选择器,你也可以这样做:
.my-target {
padding-top: 65px;
margin-top: -65px;
}
注意:如果目标元素的背景色与父元素的背景色不同,这个例子将不起作用。
例如:
<div style="background-color:red;height:100px;"></div>
<div class="my-target" style="background-color:green;height:100px;"></div>
在这种情况下,我的目标元素的绿色将覆盖65px的父元素红色。
我没有找到任何纯CSS解决方案来处理这个问题,但如果你没有另一个背景色,这个解决方案是最好的。
我之所以使用这种方法,是因为出于某种原因,其他提出的解决方案都不适合我。我保证我尽力了。
section {
position: relative;
border-top: 52px solid transparent; /* navbar height +2 */
margin: -30px 0 0;
-webkit-background-clip: padding-box;
-moz-background-clip: padding;
background-clip: padding-box;
}
section:before {
content: "";
position: absolute;
top: -2px;
left: 0;
right: 0;
border-top: 2px solid transparent;
}
如果您愿意,可以将section替换为类。
来源:跳转链接和视口定位
在Firefox 45和Chrome 52上测试。
引导版本:3.3.7
对于那些不相信我的人,我善意地准备了一个jsfiddle的解决方案:解决方案
我已经很容易地使用CSS和HTML,使用上面提到的“锚:之前”方法。我认为它是最好的,因为它不会在你的divs之间产生大量的填充。
.anchor:before {
content:"";
display:block;
height:60px; /* fixed header height*/
margin:-60px 0 0; /* negative fixed header height */
}
这似乎并不适用于页面上的第一个div,但你可以通过添加填充到第一个div。
#anchor-one{padding-top: 60px;}
这里有一个工作小提琴:http://jsfiddle.net/FRpHE/24/