我有一个固定的导航栏。其菜单项链接到带有哈希标记的书签:example.html#bookmark
点击哈希标记链接后,<h1 id="bookmark">Bookmark</h1>
应显示在导航栏下方,如下所示:
但是目前,标题元素正在被固定标题导航栏重叠:
如何防止这种情况?
HTML和CSS:
* {
margin: 0;
padding: 0;
}
.header {
height: 80px;
background: #EEE;
position: fixed;
top: 0;
left: 0;
width: 100%;
line-height: 80px;
text-align: center;
}
.header a {
color: blue;
text-decoration: none;
}
/*Ignore below this. This just creates padding for the example to scroll*/
body:before,
body:after {
content: '';
display: block;
height: 200vh;
}
&#13;
<div class="header">
<a href="#bookmark">Click this link to take you to the anchor</a>
</div>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris sit amet auctor tellus. Integer imperdiet urna vulputate pellentesque consectetur. Donec bibendum mi ac augue maximus, a porttitor risus faucibus. Aenean dui nisi, ornare et auctor vel, condimentum
vel lorem. Aliquam et mollis nisi, nec auctor diam. Ut sollicitudin vel nisl vel condimentum. Quisque ut nisl lobortis, blandit ante vitae, pellentesque lectus.</p>
<h1 id="bookmark">Bookmark</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris sit amet auctor tellus. Integer imperdiet urna vulputate pellentesque consectetur. Donec bibendum mi ac augue maximus, a porttitor risus faucibus. Aenean dui nisi, ornare et auctor vel, condimentum
vel lorem. Aliquam et mollis nisi, nec auctor diam. Ut sollicitudin vel nisl vel condimentum. Quisque ut nisl lobortis, blandit ante vitae, pellentesque lectus.</p>
&#13;
答案 0 :(得分:2)
这是一个简单的解决方法。给链接元素一个合适的大顶部填充,并用相等的负边距取消它:
h1 {
margin-top: -80px;
padding-top: 80px;
}
链接元素将视口移动到元素填充的顶部,负边距移除额外的空格。
* {
margin: 0;
padding: 0;
}
.header {
height: 80px;
background: #EEE;
position: fixed;
top: 0;
left: 0;
width: 100%;
line-height: 80px;
text-align: center;
}
.header a {
color: blue;
text-decoration: none;
}
h1 {
margin-top: -80px;
padding-top: 80px;
}
/*Ignore below this. This just creates padding for the example to scroll*/
body:before,
body:after {
content: '';
display: block;
height: 100vh;
}
<div class="header">
<a href="#bookmark">Click this link to take you to the anchor</a>
</div>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris sit amet auctor tellus. Integer imperdiet urna vulputate pellentesque consectetur. Donec bibendum mi ac augue maximus, a porttitor risus faucibus. Aenean dui nisi, ornare et auctor vel, condimentum</p>
<h1 id="bookmark">Bookmark</h1>
<p>vel lorem. Aliquam et mollis nisi, nec auctor diam. Ut sollicitudin vel nisl vel condimentum. Quisque ut nisl lobortis, blandit ante vitae, pellentesque lectus.</p>
此解决方法的限制是现在位于链接元素上方文本下方的填充。链接元素的任何背景颜色都会显示在下面,这需要自己的解决方法:)