HTML: Making a link lead to the anchor centered in the middle of the page

倖福魔咒の 提交于 2019-11-30 04:41:44
charles.cc.hsu

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!

jakub

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

There is no straight way of doing this in pure html\css. It is possible though using js, by getting the element's top location and setting the page's top position to that element's position minus half of the page's height.

Gianluca Pietrobon

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.

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

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.

Since "middle of the page" is relative to the size of the user's screen and window at any given time, you are going to have to use Javascript to achieve this, as there is no way in pure HTML/CSS to get the vertical screen width.

Extending off of charles.cc.hsu's answer, we can do this for elements of arbitrary height using the vh CSS unit, which is relative to the viewport's height.

HTML:

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

CSS:

.anchor{
    display: block;
    height: 50vh; /* 50% viewport height */
    margin-top: -50vh;
    visibility: hidden;
}

vh is supported in in IE9 and up, so it's pretty safe to use.

I'd try putting a negative margin (or other positioning method) equal to half the page height on the target anchor tag.

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!