首页 > 解决方案 > 如何使锚标签滚动而不被位置覆盖:固定区域

问题描述

我有一个顶部带有标题的页面,位置:固定,因此当用户滚动时它会停留在屏幕顶部。这很好用。

在下面的正文中有锚标签。当您单击将您带到这些锚点之一的链接时,浏览器会在最顶部显示带有该锚点的页面。即使这是在标题下。

这是一个演示问题的简化页面:

<html>
<style>
  .header {
    height: 20px;
    position: fixed;
    top: 0px;
    background-color: gray;
  }
  
  .body {
    overflow: auto;
    margin-top: 20px;
  }
</style>
<div class="header">
  This is the header.
</div>
<div class="body">
  <p><a href="#10">Line 10</a> <a href="#20">Line 20</a></p>
  This is the body.<br/> Line 2<br/> Line 3<br/> Line 4<br/> Line 5<br/> Line 6<br/> Line 7<br/> Line 8<br/> Line 9<br/>
  <a name="10" /> Line 10<br/> Line 11<br/> Line 12<br/> Line 13<br/> Line 14<br/> Line 15<br/> Line 16<br/> Line 17<br/> Line 18<br/> Line 19<br/>
  <a name="20" /> Line 20<br/> Line 21<br/> Line 22<br/> Line 23<br/> Line 24<br/> Line 25<br/> Line 26<br/> Line 27<br/> Line 28<br/> Line 29<br/> Line 30<br/> Line 31<br/> Line 32<br/> Line 33<br/> Line 34<br/> Line 35<br/> Line 36<br/> Line 37<br/>  Line 38<br/> Line 39<br/> Line 40<br/>
</div>

</html>

单击“第 10 行”链接,它会显示标题,在标题正下方,第一个可见的内容是...第 11 行。

我希望它能够正常工作,以便如果您单击第 10 行的链接,则可以看到第 10 行。

标签: htmlcss

解决方案


这里已经有针对此类问题的回应。它使用以下技巧padding-top: size; margin-top: -size;

.body a {
  /* Adjust here the size */
  padding-top: 20px;
  margin-top: -20px;
}
<html>
<style>
  .header {
    height: 20px;
    position: fixed;
    top: 0px;
    background-color: gray;
  }
  
  .body {
    overflow: auto;
    margin-top: 20px;
  }
</style>
<div class="header">
  This is the header.
</div>
<div class="body">
  <p><a href="#10">Line 10</a> <a href="#20">Line 20</a></p>
  This is the body.<br/> Line 2<br/> Line 3<br/> Line 4<br/> Line 5<br/> Line 6<br/> Line 7<br/> Line 8<br/> Line 9<br/>
  <a name="10" /> Line 10<br/> Line 11<br/> Line 12<br/> Line 13<br/> Line 14<br/> Line 15<br/> Line 16<br/> Line 17<br/> Line 18<br/> Line 19<br/>
  <a name="20" /> Line 20<br/> Line 21<br/> Line 22<br/> Line 23<br/> Line 24<br/> Line 25<br/> Line 26<br/> Line 27<br/> Line 28<br/> Line 29<br/> Line 30<br/> Line 31<br/> Line 32<br/> Line 33<br/> Line 34<br/> Line 35<br/> Line 36<br/> Line 37<br/>  Line 38<br/> Line 39<br/> Line 40<br/>
</div>

</html>


推荐阅读