<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS 锚点定位示例</title>
<style>
/* 定义一个固定高度的容器,用于演示滚动效果 */
body {
height: 2000px;
}
/* 定义锚点目标元素的样式 */
.anchor-point {
background-color: lightblue;
padding: 20px;
margin: 50px 0;
}
/* 使用 CSS 的 scroll-margin-top 属性来调整滚动时的位置 */
.anchor-point::before {
content: '';
display: block;
height: 60px; /* 这个值应该与页面顶部导航栏的高度一致 */
margin-top: -60px;
visibility: hidden;
pointer-events: none;
}
</style>
</head>
<body>
<nav style="position: fixed; top: 0; width: 100%; background: white;">
<a href="#section1">跳转到第一部分</a>
<a href="#section2">跳转到第二部分</a>
<a href="#section3">跳转到第三部分</a>
</nav>
<div id="section1" class="anchor-point">
<h2>第一部分</h2>
<p>这是第一部分内容。</p>
</div>
<div id="section2" class="anchor-point">
<h2>第二部分</h2>
<p>这是第二部分内容。</p>
</div>
<div id="section3" class="anchor-point">
<h2>第三部分</h2>
<p>这是第三部分内容。</p>
</div>
</body>
</html>
HTML 结构:
#section1
, #section2
, #section3
)。id
来标识,并且应用了 .anchor-point
类。CSS 样式:
body
设置了一个较大的高度,以便能够看到滚动效果。.anchor-point
类定义了每个部分的样式,包括背景颜色和内边距。.anchor-point::before
使用了伪元素来调整滚动位置。通过设置 height
和 margin-top
,可以确保在点击锚点链接时,内容不会被固定在顶部的导航栏遮挡。滚动行为:
::before
伪元素的存在,内容会在导航栏下方正确显示,不会被遮挡。这个示例展示了如何使用 CSS 来实现平滑的锚点定位,并且避免了内容被固定导航栏遮挡的问题。
上一篇:css压缩在线
下一篇:css超出部分省略号
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站