使用填充可以避免这个问题。由于边距不包含在内容边界中,因此浏览器会忽略它。
<!doctype html>
<html>
<head>
<style type="text/css">
body {
margin: 0;
padding: 0;
}
div {
padding-top: 10px;
}
</style>
</head>
<body>
<div id="1">How can I jump to a point slightly above the fragment identifier?<br/>
up vote 2 down vote favorite</div>
<div id="2">
I don't like how the fragment identifier jumps to the actual point of where the content begins on the page. It looks awkward having the box start right at the top of the screen. It kind of bugs me. So I was using an anchor with a name attribute above it, set to display: block so that it would pay attention to the 10px margin on the top of the box below it. Using this method, it essentially jumped down to that content, with 10px spacing between the start of the content and the actual top edge of the browser window.</div>
<div id="3">
But it seems that I'm no longer allowed to do this in HTML5, as when I try to validate the page, I get this nice warning:</div>
<div id="4">
The name attribute is obsolete. Consider putting an id attribute on the nearest container instead.</div>
<div id="5">
I can't just change all the name attributes to id attributes because it becomes an empty hyperlink rather than a named anchor (I've also tried, the display: block no longer gets applied to it).</div>
<div id="6">
So, given a group of divisions, like so:</div>
<div id="7">Content</div>
<div id="8">Content</div>
<div id="9">Content</div>
<div id="10">Content</div>
<div id="11">
and assuming that they all have a 10px margin applied to the top of them, is there any way to re-apply the IDs to them so that when I use fragment identifiers to jump to different spots, it still includes the 10px space between the content and the top edge of the browser window?</div>
<div id="12">
Note: I've tried applying the ID directly to each division, but the browser ignores the margin on the element when determining where to jump.</div>
<div id="13">
html fragment-identifier</div>
</body>
</html>