Home > Back-end >  How to avoid jumping when click on anchor link
How to avoid jumping when click on anchor link

Time:08-31

I want to show/hide content using purely CSS without JavaScript. I reached on this solution.

When I click on the link it jump down in page. I need pure CSS solution, how to stop it to jump?

p[id^="detailView-"] {
  display: none;
}

p[id^="detailView-"]:target {
  display: block;
}
<a href="#detailView-1">Show View1</a>
<p id="detailView-1">View1</p>

<a href="#detailView-2">Show View2</a>
<p id="detailView-2">View2</p>

CodePudding user response:

Just arrange your html so the anchor tags are at the top like so

p[id^="detailView-"] {
  display: none;
}

p[id^="detailView-"]:target {
  display: block;
}
<a href="#detailView-1">Show View1</a>
<a href="#detailView-2">Show View2</a>

<p id="detailView-1">View1</p>
<p id="detailView-2">View2</p>

CodePudding user response:

In this situation, instead of toggling between:

  • display: none
  • display: block

you can toggle between:

  • visibility: hidden
  • visibility: visible

The difference betwen the two properties is that:

  • visibility maintains page-space for an element, even when that element is invisible
  • display: none will actually remove the element from the page and collapse the space that it was occupying

Working Example:

p[id^="detailView-"] {
  visibility: hidden;
}

p[id^="detailView-"]:target {
  visibility: visible;
}
<a href="#detailView-1">Show View1</a>
<p id="detailView-1">View1</p>

<a href="#detailView-2">Show View2</a>
<p id="detailView-2">View2</p>


Further Reading:

  • Related