锚点设置距离顶部高度的方法

本文探讨了网页中锚点定位出现偏移的现象,并通过具体的HTML与CSS代码示例展示了如何创建不同高度的层来确保锚点准确到达指定位置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>锚点位置偏移</title>
<style>
body,h2,p{
margin:0;
padding:0;
}
h2,p{
width:500px;
position:relative;
}
p{
height:400px;
background:#CCC;
z-index:2;
}
p.extra{
margin:0 0 500px;
}
h2{
margin:-200px 0 0;
border-top:200px solid #000;
z-index:1;
background:#06F;
}
#anchor1{
margin:0;
}
span{
position:fixed !important; position:absolute;
top:200px;
left:510px;
}
#menu{ background:#CCC; position:fixed !important; position:absolute;left:0px; top:0px; z-index:999; }
</style>
</head>
<body>
<div id="menu"><a href="#anchor1">去往锚点1</a> <a href="#anchor2">去往锚点2</a> <a href="#anchor3">去往锚点3</a> <a href="#anchor4">去往锚点4</a> <a href="#anchor5">去往锚点5</a></div>
<h2 id="anchor1">锚点111111111111111111111</h2>
<p>有一定高度的层</p>
<h2 id="anchor2">锚点222222222222222222222</h2>
<p>有一定高度的层</p>
<h2 id="anchor3">锚点333333333333333333333</h2>
<p>有一定高度的层</p>
<h2 id="anchor4">锚点444444444444444444444</h2>
<p>有一定高度的层</p>
<h2 id="anchor5">锚点555555555555555555555</h2>
<p class="extra">底端需要一定高度才可以保证滚动条有足够高度让标题5到达指定位置</p>
<span>←目标在这里</span>
</body>
</html>

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值