简体   繁体   中英

Trying to focus on a specific div on click of an anchor link

I am trying to get focus on a specific div on click of an anchor link. Here is the code

<a href="somepage.html#divname">Link</a>

I am facing a problem that the view is rendered from different partial views like header footer etc. The header contains the link to a particular div from another view and it has a sticky navbar. When I click the link on nav bar it does focus on the div. But some part of div hides behind the header navbar. Which looks clumsy according to the UI perspective. Here is the navbar code:

  <nav><li><a href="somepage.html#divname">Link</a></li></nav>

The example code for page div could be something like

  <div id="divname">Some Content</div>

Please give me a clue how can I get the div to show just beneath the sticky menu bar.

Try with giving some margin-top to the div you want to focus on clicking, so that, the navbar will not hide your div and then change your href from

href="somepage.html#divname" 

to

href="#divname" 

only. Always give unique ids or classes to the elements in HTML so that the machine will not get confused between them and treat two different elements the same way. Hope this will work for you. If not post a response for help.

There's plenty of questions like this one on StackOverflow. Try this one for example: https://stackoverflow.com/a/59380086/1973005

You can add a pseudo-element (::before) to the linked element in CSS, using the following settings. This creates an invisible block above the linked element which again creates an offset for the linked element position, since the top of that pseudo-element will actually be the position of the link anchor.

.anchor_offset::before {
  display: block;
  content: ' ';
  height: 10em; // Whatever height your navbar is
  margin-top: -10em; // Whatever height your navbar is
  width: 100%;
  visibility: hidden;
}
<div id="divname" class="anchor_offset">Some Content</div>

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