HTML: Making a link lead to the anchor centered in

2019-02-05 20:09发布

I have a link to an anchor on my html page. When the link is clicked it causes the page to scroll to the anchor so that the anchor is at the very top of the visible part of the page. How can I make the page scroll so that the anchor will be in the middle of the page?

10条回答
闹够了就滚
2楼-- · 2019-02-05 20:47

I found a solution Anchor Links With A Fixed Header posted by Phillip, he is a web designer. Phillip added a new EMPTY span as the anchor position.

<span class="anchor" id="section1"></span>
<div class="section"></div>

then put the following css code

.anchor{
  display: block;
  height: 115px; /*same height as header*/
  margin-top: -115px; /*same height as header*/
  visibility: hidden;
}

Thanks, Phillip!

查看更多
Melony?
3楼-- · 2019-02-05 20:51

if you want without blank space do it like this:

<h2 id="jump_tag" style="padding-top: 500pt; margin-top: -500pt;"></h2>

but, you'll still have to regulate height from javascript

查看更多
forever°为你锁心
4楼-- · 2019-02-05 21:01

Firefox supports setting a padding-top property on the named anchor. From there, you could set a cookie via javascript that contains the browser's dimensions, and adjust your padding-top accordingly server-side. To the end user, it would look like its pure html/css, but noam is correct in that a wee bit of JS is needed to get the browser's dimensions, since it doesn't give you this information without a little coercion.

查看更多
兄弟一词,经得起流年.
5楼-- · 2019-02-05 21:03

Determine what part of your page you actually want at the top, and place the anchor there instead. You won't be able to change the way browsers interpret anchors - at least not without upsetting your users.

查看更多
对你真心纯属浪费
6楼-- · 2019-02-05 21:05

html:

<a id="anchor">NEWS</a>

css:

#anchor{
position: relative;
padding-top: 100px; //(whatever distance from the top of the page you want)
}

worked fine for me

查看更多
甜甜的少女心
7楼-- · 2019-02-05 21:05

Place a <span class="anchor" id="X"> then style the anchor class like:

.anchor {
  position: absolute;
  transform: translateY(-50vh);
}

With -50vh the anchor will scroll in the middle of the screen.

查看更多
登录 后发表回答