简体   繁体   中英

Vertically center div when clicking on an anchor link

What I want to do is have an anchor link that links to a div lower on the page. Normally the way this works is it scrolls down to the anchor, positioning it at the top of the window. Is there a way to get it to scroll down and center it instead?

I've sort of worked around this by putting another div inside, giving it an absolute position of top: calc(-50vh + 200px);, and making this the anchor.

This works fine in Firefox and IE, but not in Chrome. I'm assuming this isn't the best way to do it anyway. I'm sure there's some way of accomplishing this with Javascript, but I haven't found any working examples. Does anyone have a clue as to how this can be accomplished?

You could try:

window.scrollTo(x, y);

If you don't want to hardcode the value for y, you can use jQuery's .position() method to find the value for y.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM