Adding a field for a link inside a page

Links within the page scroll through the content at the top of the browser window. Is there any way to add margin to this? I will use some javascript to guide scrolling, but would like to have a viable backup.

So, in short, can I add a marker in CSS that will add some space between the top of the browser window and the section when it is a link to the page.

HTML:

<nav> <a href="#test">TEST</a> </nav> <div class="section"> <a name="test"></a> <p>This content should be offset from the top of the page when scrolled to</p> </div> 
+4
source share
2 answers

The preferred way to link to a page is to use an identifier instead of the name attribute.

 <a href="#test"> 

must match:

 <div id="test"> 

Here you can easily add a registration to the top of the #test div, and that will be your scroll position.

Example: http://tinkerbin.com/EvV7byy9

+5
source

Hmm, I would put anchors in each section so that they are located absolutely, about 10 pixels down from the beginning of the section. It will look like this:

 .section { position: relative; } .section > a { position: absolute; top: 10px; } 

This is essentially a 10x field. You can adjust the top value accordingly to change the field / padding. I also used the direct child operator (>), so the links in the paragraphs will not be affected.

Also, as @NathanManousos mentioned, you should no longer use the name attribute, but the ID attribute. Relative document links will scroll to the identifier of any element, not just links. You can put the identifier in each of the div sections and use the registration to scroll to the top of the div, and filling it will cause the actual content to be even lower in the div.

 <style> .section { padding-top: 10px; } </style> ... <nav> <a href="#test">TEST</a> </nav> <div class="section" id="test"> <p>This content should be offset from the top of the page when scrolled to</p> </div> 
0
source

Source: https://habr.com/ru/post/1383263/


All Articles