Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I have an issue when I link to a specific section of a page?

Tags:

html

I made a lengthy page that I'm testing on my computer. Since it's so long, I added a table of contents to the top. Under the table of contents are some links that, when clicked, take you to a specific section of the page. Here's an example of the markup I used:

<h4>Table of Contents</h4>
<ul>
    <li><a href="#gotolink">Link</a></li>  
</ul>
<h3><a name="gotolink">Link</a></h3>
    <p>some stuff here</p>

It works fine. The problem is that I also have a fixed header, as in you always see the header no matter where you are on the page, and when I click a link under the table of contents it takes me to that section of the page but the header ends up covering the <h3> stuff. I want to make it so that when you click a link it takes you to that section of the page, but the section will be in the middle of your screen, not the top, so the header won't cover anything.

like image 264
Steph Connelly Avatar asked Nov 13 '22 13:11

Steph Connelly


1 Answers

Solution

You can do this by setting position: relative; on the target <a> element; just give the header a set height, and set top: -[header height] on the <a>.

Demonstration

Here's a JSFiddle. Click the Link at the top of the long page (please excuse the vast amount of Lorum Ipsum). The page will jump down to the red title.

CSS

body {
    margin-top: 20px;    /* Same height as header */
}

#header {
    position: fixed;
    background: black;
    color: white;
    height: 20px;
    line-height: 20px;
    width: 100%;
    top: 0;
}

h3 a {
    position: relative;
    top: -20px;    /* Negative header height */

    /* Don't select anchor */
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    -o-user-select: none;
    user-select: none;
}

Caveats

  • The header must have an explicit height so offsets can be set correctly.
  • As the <a> is offset from the containing element (<h3> in this case), user selection is disabled with user-select: none. This means that any text in the <a> isn't selectable. This is why I didn't wrap the <h3>'s text in it in the JSFiddle demo.
  • This won't place the target title in the middle of the screen, however it will position it underneath the header.
like image 111
Bojangles Avatar answered Dec 22 '22 14:12

Bojangles