有没有办法在CSS中保留锚?

Pie*_*ard 20 html css anchor

我有一个固定的标题高度50px.在我的身体里,我有很多锚点.问题是,当我点击指向锚点的链接时,锚点出现在我的固定标题下,我丢失了50px的内容(我需要向上滚动50px来读取标题下的内容).

有没有办法保留50px的锚?我的身体充满了很多盒子(div),它们之间有一个边缘,所以我不能放置50px的空div然后锚定它.

HTML:

<div id="header"></div>
<div id="content">
     <div class="box" id="n1"></div>
     <div class="box" id="n2"></div>
     <div class="box" id="n3"></div>
</div>
Run Code Online (Sandbox Code Playgroud)

CSS:

#header{
    height: 40px;
    width: 100%;
    margin: 0px;
    padding: 0px;
    position: fixed;
    text-align: center;
    z-index:2;
}

#content{
    padding-top: 50px; 
    margin: 0px;
}

.box {
    width: 80%;
    margin-left: auto;
    margin-right: auto;
    vertical-align : top;
    padding: 1.4%; /* Keep it in percent (%) */
    margin-bottom: 30px;
    min-height: 200px;
}
Run Code Online (Sandbox Code Playgroud)

dmo*_*moz 21

欢迎来到未来:

.box {
  scroll-margin-top: 50px;
}
Run Code Online (Sandbox Code Playgroud)

来源: https: //css-tricks.com/almanac/properties/s/scroll-margin/


mrt*_*man 6

如果标题是真正固定的,那么将锚点放在可滚动的div中.然后包含锚点的div将滚动而不是整个页面.访问小提琴,然后单击anchor1.它转到了anchor2.等等.

http://jsfiddle.net/mrtsherman/CsJ3Y/3/

css - 设置隐藏在body上的溢出以防止默认滚动.在顶部和底部设置的新内容区域上使用绝对位置.这会强制它伸展以适应剩余的视口窗口.

body { overflow: hidden; }
#header { position: fixed; top: 0; left: 0; width: 100%; height: 50px; background: gray; border: 1px solid black; }
#content { 
    overflow: scroll; 
    position: absolute;
    top: 50px;
    bottom: 0px;
    width: 100%;
    border: 1px solid blue; 
}
Run Code Online (Sandbox Code Playgroud)

HTML

<div id="header">header</div>
<div id="content">
    <div>
        Page Content <br />
        <a id="a1" href="#anchor2" name="anchor1">Anchor 1</a>                
        <a id="a2" href="#anchor1" name="anchor2">Anchor 2</a>   
    </div>
</div>?
Run Code Online (Sandbox Code Playgroud)