githubmarkdownanchor

Github Markdown anchor only linking to top of the page


I'm not sure if this place would be appropriate to ask about Github wiki markdown issues. I'll remove it if it is so.

So, I am writing up a wiki page for a repository, and I've been trying to add anchors. However, the anchor only seems to lead to reload the page, or lead to the top of the page. I'm pretty sure my syntax is correct, but I don't know what's wrong.

I have example as:

Link as: <a name="#dinpanel"></a>

Then I access it with: [text to show](myrepositoryweburl#dinpanel) Also if I just type "myrepositoryweburl#dinpanel" to the URL, it still loads to top of the page. I'm wondering what is going on with Markdown. Any help would be appreciated!


Solution

  • Use a Markdown header rather than a raw HTML anchor.

    As documented in github/markup, after the Markdown is converted to HTML...

    The HTML is sanitized, aggressively removing things that could harm you and your kin—such as script tags, inline-styles, and class or id attributes.

    While name attributes are not specifically mentioned, id attributes are and they serve a similar function. A previous version of the document linked to the sanitation script, which does not include the name attribute in the whitelist of approved attributes. In other words, GitHub's sanitizer is removing your name attribute.

    In fact, if you use your browser's view sourcefeature, I expect you will find that the name attribute is missing from the HTML on that page. However, all is not lost. If you notice, step 4 includes (emphasis added):

    The HTML is passed through other filters in the html-pipeline that add special sauce, such as emoji, task lists, named anchors, CDN caching for images, and autolinking.

    In other words, every header (h1, h2,... h6) in the document is assigned a unique id. Therefore, you can point to the id assigned to any header, and you will get the behavior you desire.

    # Din Panel
    
    ...
    
    [link](#din-panel)
    

    Note that to generate an id, all characters are converted to lowercase ASCII characters, all punctuation (expect hyphens and spaces) is removed, and all spaces are replaced with hyphens (-). Finally, if needed, an incrementing number is appended to the end to ensure each id is unique.

    If you are having trouble correctly guessing the auto-generated id, you can always view the generated page on GitHub, and when hovering over the header, an anchor icon will appear next to the text. That icon will contain a link to that specific header with the correct id. Or you could use your browser's view source feature (or the inspect developer tool) to determine the id assigned to the header.