Skip to content

Instantly share code, notes, and snippets.

@asabaylus
Created July 8, 2012 14:12
Show Gist options
  • Save asabaylus/3071099 to your computer and use it in GitHub Desktop.
Save asabaylus/3071099 to your computer and use it in GitHub Desktop.
Github Markdown Heading Anchors

Anchors in Markdown

To create an anchor to a heading in github flavored markdown. Add - characters between each word in the heading and wrap the value in parens (#some-markdown-heading) so your link should look like so:

[create an anchor](#anchors-in-markdown)

@duhaime
Copy link

duhaime commented Apr 19, 2017

@Zyxan This technique works, though the gist could be a little more explicit.

To create an anchor tag in github markup, you just need to create a heading element. Example:

#### Installation guide
Here would be some installation instructions

When GitHub transforms this markdown into html, the #### Installation guide line above will be represented as:

<a href='#installation-guide' id='installation-guide' class='anchor' aria-hidden='true'>Installation guide</a>

You can link to this href with a link that looks like this:

[Read our installation guide](#installation-guide)

I hope that helps!

@eeholmes
Copy link

eeholmes commented May 4, 2017

Is there a way to specify the anchor name? As soon as I change my section name, all my links will break. I want to specify the anchor like normal for markdown but the html generated from my README.md file is not working as normal for markdown.

So my README.md has

# This is a section name that I might change {#foo}

Normally, this sort of link would work [link](#foo) but it is not working in the html autogenerated by Github from my README.md file.

@eksperimental
Copy link

thank you @eeholmes, such a GREAT ADVICE!

@wayri
Copy link

wayri commented Jun 18, 2017

Take me where
I guess markdown behaves quite similar to html. I will attach an example below;

[Take me there](#there_you_go)
[Take me where](#here)

I defined two links with anchor names

below is the first anchor

<a name="there_you_go"></a>Take me there

here is the second anchor

<a name="here"></a>Take me where

here is it in practice

Take me there will take you down
Take me where will take you up
/
Take me there
/
blank space for test
/
/
/
/
/
/
blank space end
/
/

So it does work. Hope this helps

@Vic-ST
Copy link

Vic-ST commented Aug 14, 2017

@wayri Thanks! that works for me.

@kne42
Copy link

kne42 commented Aug 19, 2017

@janluong One would think that

# [](#my-custom-anchor-name)My Header Name

would result in what we want – but in GitHub Pages, it is unfortunately irrelevant as it would autogenerate the anchor as #my-header-name instead of #my-custom-anchor-name as one would expect.

I found inserting the following in your .md file to work quite nicely:

your markdown here
<h1 id="my-custom-anchor-name">
  My Header Name
</h1>
your markdown here

Best,
Kira

@kesupile
Copy link

kesupile commented Sep 23, 2017

Works like a charm. Make sure the fragment link is all in lowercase

# [Heading Link](#section-i-want)

## [Section I Want] 

@JenkinsY94
Copy link

I wonder how to create anchor to a sub-heading. For example:

Head 1

Head 2

and I want to add anchor to head 2. I tried this but not working:
[create an anchor](#head-2)

@wprestong
Copy link

I use the "Display #Anchors" extension to Chrome, and also "Markdown Viewer". When I look at a markdown page in Chrome, I can then see how the anchors are spelled. Some have "-" inserted at the beginning, and some don't, and I don't know what the rules are, but if I follow the spelling used by Chrome, the links work, at least with Chrome.

@yegeniy
Copy link

yegeniy commented Dec 14, 2017

The anchors don't work if you have an anchor link to the current page in GitHub Pages, generated from MarkDown via https://github.com/blog/2289-publishing-with-github-pages-now-as-easy-as-1-2-3

^ anchors links in header no longer work in GH Pages

The only solution I see is putting HTML into your markdown...

Something along the lines of this at the top of your page:

<a id="-"/>

And instead of [hyper](links) such as [^](#) or [^](#-) use something like the following just above your headers:

<a href="#-">`^`</a> - (click to go to first anchor of this comment)

# Header without an anchor link

this would look something like this:

^ - (click to go to first anchor of this comment)

Header without an anchor link

@Kristine94
Copy link

Thanks bro!

@biscaboy
Copy link

biscaboy commented Feb 2, 2018

Thanks for the tip!

@tibdex
Copy link

tibdex commented Feb 8, 2018

If you want stable anchors to have permalinks in your CHANGELOG.md you can do as explained here.

@alete89
Copy link

alete89 commented Feb 16, 2018

I send you love!

@g10guang
Copy link

What about all characters in header is all chinese. For example 你好。

[你好](#你好)

Cannot work.

@Algomorph
Copy link

Algomorph commented Apr 16, 2018

For titles with periods (".") in them this doesn't work. Frustrating, because I wanted to put the section/subsection numbers into the headers, i.e. "# 2.3.4 Some Stuff"
[EDIT] Oh, the periods just have to be skipped in the anchor. Would have been useful to know...

@ChenYingChou
Copy link

ChenYingChou commented Apr 20, 2018

  • Convert to lowercase letters
  • Replace each space with '-'
  • Remove punctuations other than "-" and "_"
  • Remove CJK punctuations
function GithubId(val) {
	return val.toLowerCase().replace(/ /g,'-')
		// single chars that are removed
		.replace(/[`~!@#$%^&*()+=<>?,./:;"'|{}\[\]\\–—]/g, '')
		// CJK punctuations that are removed
		.replace(/[ 。?!,、;:“”【】()〔〕[]﹃﹄“”‘’﹁﹂—…-~《》〈〉「」]/g, '')
}

@caub
Copy link

caub commented May 31, 2018

@srafay
Copy link

srafay commented Jul 27, 2018

@shasapo
Copy link

shasapo commented Aug 1, 2018

@splaisan
Copy link

splaisan commented Aug 1, 2018

  1. declare target mark in a regular MD header
    ## My header with a lot of words, and punctuation
    becomes
    ## <a name="some-text">My header with a lot of words, and punctuation</a>

  2. link to the mark with
    [Go to my mark](#some-text)

@sravan953
Copy link

Thanks!

@montaro
Copy link

montaro commented Aug 20, 2018

Thanks @asabaylus
Thanks @chop-suey for the tip, this workaround made it work for me
https://gist.github.com/asabaylus/3071099#gistcomment-1574926

@derianpt
Copy link

Thanks man!

@nisusam
Copy link

nisusam commented Oct 22, 2018

Thanks @asabaylus

@RobertDelwood
Copy link

RobertDelwood commented Nov 7, 2018

None of these work for me. As an example, I use

[Heading Link](#section-i-want)
...
## Section I Want 

And the link goes to a blank page as http://localhost:8080/v2/#section-i-want

Any ideas? I'm using a Mulesoft's API Console, RAML, single page application.

@NirViaje
Copy link

NirViaje commented Dec 10, 2018

Work or not?

[Work or not?](#work-or-not)

no, am I wrong?

@PythonCoderAS
Copy link

Thank you so much.

Test:

Help

help

@imthenachoman
Copy link

The code that creates the anchors is here:
https://github.com/jch/html-pipeline/blob/master/lib/html/pipeline/toc_filter.rb

  1. It downcases the string
  2. remove anything that is not a letter, number, space or hyphen (see the source for how Unicode is handled)
  3. changes any space to a hyphen.
  4. If that is not unique, add "-1", "-2", "-3",... to make it unique

Thank you for this information @TomOnTime. I was able to use it to create https://imthenachoman.github.io/nGitHubTOC/. It's a simple webpage to create TOC from GitHub markdown..

@ttous
Copy link

ttous commented Feb 26, 2019

Thanks @imthenachoman! It helped me realise that this header:
## [0.0.2] - 2019-02-24
should be linked to with this anchor:
[0.0.2](#002---2019-02-24)
which may not be totally intuitive, but @TomOnTime explained it clearly 👍 .

@gfilipiak
Copy link

👍

@afelopez
Copy link

Thanks a lot! it's very useful.

@Nandtrocity
Copy link

This is another "thank you" message.

@khastation
Copy link

@Velojet
Copy link

Velojet commented Jun 9, 2019

My problem was linking to subheadings with the same name as a subheading in another section.
@splaisan provided me with the solution: a named anchor link, so:
# Section 1 Heading
## Subheading
# Section 2 Heading
## <a name="subheading-2">Subheading</a>

@ThanasisMattas
Copy link

ThanasisMattas commented Aug 10, 2019

Can the anchor (or a link) at a header be written in a smaller fond?

Tried <span style="font-size:small;">[link_name]</span>, but it didn't work on github.

@capgunmedia
Copy link

Does this need to be posted to a live server to work?

@lenzpaul
Copy link

It's okay, I fixed it. I realized that the anchor can work fine without the inclusion of the punctuation. See example below

[Ready, set, GO!](#ready-set-go)

will result in an anchor that works just fine.

Thanks! Just what I was looking for

@ScriptAutomate
Copy link

I referenced this conversation on StackOverflow, since this gist conversation includes interesting comments about anchors all throughout!

@teerasej
Copy link

One of the most useful gist, Cheer!

@toymil
Copy link

toymil commented Feb 2, 2020

* Convert to lowercase letters

* Replace each space with '-'

* Remove punctuations other than "-" and "_"

* Remove CJK punctuations
function GithubId(val) {
	return val.toLowerCase().replace(/ /g,'-')
		// single chars that are removed
		.replace(/[`~!@#$%^&*()+=<>?,./:;"'|{}\[\]\\–—]/g, '')
		// CJK punctuations that are removed
		.replace(/[ 。?!,、;:“”【】()〔〕[]﹃﹄“”‘’﹁﹂—…-~《》〈〉「」]/g, '')
}

For anyone trying to deal with unicode charecters:

I think exclude is better then include every possible punctuation.

This regex [^\w\u4e00-\u9fff\- ] will exclude all word, underscore, hyphen, space, CJK character, and select everything else.

One demonstration of the superiority of this is that it will include emojis while your regex does not.

@sunguard
Copy link

@ochen1
Copy link

ochen1 commented Apr 23, 2020

Thank you!

@antonio-petricca
Copy link

Thank you

@sunilyadav8
Copy link

Works like a charm. Make sure the fragment link is all in lowercase

# [Heading Link](#section-i-want)

## [Section I Want] 

Thank you.

@Mardiniii
Copy link

Thank you so much for this gist! 🙌 🙌 🙌 🙌

@holylander
Copy link

thanks a lot for this info :)

@XDracam
Copy link

XDracam commented May 21, 2020

Shows up in Google Search, thanks for spreading the knowledge!

@svakam
Copy link

svakam commented Jun 5, 2020

Sweeeeet

@dev0284
Copy link

dev0284 commented Jun 17, 2020

Here's a tip -- if you're having trouble with your anchor not working due to misspellings or odd characters, simply hover over your heading on Github, then hover or click the link icon that appears to the left. You can then right click to copy the link location, left click it to go to the URL and view it in your address bar, or simply stay hovered over it and view it in the status bar of your browser.

Great tip. Thanks!

@ntrel
Copy link

ntrel commented Jun 29, 2020

Does Markdown have any way of just linking to a heading without repeating yourself?

I want to link to [Heading] without having to type [Heading](#heading).

Heading
-------

When Heading is long this is very tiresome.

@JeffreyBenjaminBrown
Copy link

Linking to a subsection of another file in the same repo is also possible:

[description](../relative/link/to/file.md#section-name-with-dashes-instead-of-spaces)

Capitalization matters.

Some extraneous newlines make the above a little more readable:

[description]
(../relative/link/to/file.md
#
section-name-with-dashes-instead-of-spaces)

I imagine the same trick works if you give an absolute link to a markdown file in a different repo.

@HugoCortell
Copy link

How can I make an anchor that does not render?
I have a page that is constantly updated and I wanted to make a link that leads to the button of the page, so I added a textless anchor to the button, but it does not work!

@rupertjeff
Copy link

rupertjeff commented Jul 6, 2020

@ntrel Try this alternate method of linking:

I want to link to [Heading] without having to type [Heading].

Heading
--------

... more copy here as needed...

[Heading]: #heading

Wherever it sees [Heading], Markdown will look for a corresponding link definition, and if it finds one, it will associate it, as long as it's an exact match.

@ntrel
Copy link

ntrel commented Jul 7, 2020

@rupertjeff That's useful if I have multiple links to a long anchor in the same document. I meant that if the link title and anchor id are the same except for the automatic lowercase and hyphenation, it would be nice not to have to repeat the anchor, just like on a wiki.

@jesshart
Copy link

Note if you test this in "Edit file" mode, you may be warned that it will take you off the page. In my case, I got this warning. Once I committed the changes my anchor link was working perfectly.

@Pavivenkatesan
Copy link

What if I have two headings with same name and I want the anchor link to take me to the latter one and not the former?

@saulhg
Copy link

saulhg commented Aug 19, 2020

I am using Markdown web part in Sharepoint and the anchors were not working for me... Then, I realised why.
I wrote #Definición (note the Spanish accent in the "o") and was trying to link to it with [Ir a la definición](#definición).
This didn't work, But then, I checked by viewing source in the Chrome browser and noticed that the accented o was omitted. So, writing [Ir a definición](#definicin) worked just fine!
So, characters like á,é,í,ó,ú,Á,É,Í,Ó,Ú,Ñ,ñ are just omitted in anchors.

@chongchonghe
Copy link

Thanks! Very helpful.

Is there a way to create a short name for the section title? Something like this:

# [Star Formation Theory][sft]
[Reference to this section](#sft)

@rv404674
Copy link

If one of my heading is this "## What is goRubu? 🚀", then doing this isn't working?

  • What is goRubu?

Any idea how to fix this?

Copy link

ghost commented Nov 4, 2020

👍 thank you

@Praful932
Copy link

Easiest Way I found to fix this was after writing down the headings on github, just do inspect element from the browser and find what the anchor links are 😁

@Cavitedev
Copy link

Write with this structure

[anchor](#heading-to-achor)

you can write anything on anchor.
on the heading you can simply copy and paste the link when clicking on this symbol
image...
on github.
The url will end with the #heading-to-anchor text
image...

@yaronelh
Copy link

yaronelh commented Nov 26, 2020

A few additional comments that I don't know if were mentioned is that

  1. It doesn't matter if you're using # ## ### to size your titles they link will always have only one # like this [text text](#link-text)
  2. Obviously your title Won't have - rather they'll have spaces, In the link itself replace spaces with dashes
  3. If you're title ends with that a ? remove the ? in the link not [text text](#link-text?) rather [text text](#link-text)
  4. At the point of writing, anchor links are not reflected in the preview, you'll have to commit to see if it worked

Hope these helped someone

@AlphaPav
Copy link

Works like a charm. Make sure the fragment link is all in lowercase

# [Heading Link](#section-i-want)

## [Section I Want] 

thanks so much!!!

@mcascone
Copy link

This is great, thanks! I just wanted to add:

  1. At the point of writing, anchor links are not reflected in the preview, you'll have to commit to see if it worked

In VSCode with the GitHub Markdown Preview extension, anchor links work perfectly, as do file links.

@yaronelh

@showcove
Copy link

@Aissaoui-Ahmed
Copy link

@Lemanja
Copy link

Lemanja commented Feb 16, 2021

Thank you so much, I find this works amazingly! :)

@soniatechie
Copy link

I have found here (https://docs.microsoft.com/en-us/contribute/how-to-write-links) that you can create explicit anchor links but it is not recommended.

Why is it not recommended if you can used this to solve the problem with Spanish words with accents?

## <a id="anchortext" />Header text

@DevDotKP
Copy link

DevDotKP commented May 9, 2021

How do I use anchor links to link to another page on the same Wiki?

@firedynasty
Copy link

firedynasty commented May 20, 2021

Here's a tip -- if you're having trouble with your anchor not working due to misspellings or odd characters, simply hover over your heading on Github, then hover or click the link icon that appears to the left. You can then right click to copy the link location, left click it to go to the URL and view it in your address bar, or simply stay hovered over it and view it in the status bar of your browser.

Thanks a lot! droplet icloud : there is a hyphen (#droplet-icloud) to a heading that looks like "# Droplet icloud"

@IZVRStudio
Copy link

How can I link a header with numbers?
Example:
# 1.1 Header

@jabielecki
Copy link

How can I link a header with numbers? Example: # 1.1 Header

Try #11-header

@IZVRStudio
Copy link

Doesn't work. It creates an empty link that doesn't go anywhere :(

@Velojet
Copy link

Velojet commented Sep 28, 2021

How can I link a header with numbers? Example: # 1.1 Header

Surround your header text with a named anchor link (e.g. <a name="1-1-header">1.1 Header</a>) and link to that.

@stasyao
Copy link

stasyao commented Nov 17, 2021

How can I link a header with numbers? Example: # 1.1 Header

The header at the top includes a link that leads to the header at the bottom.
Upd. You can use any id, its value does not have to match the text of the element.

# 1.1 [Header](#1.1)   

...some text...

# 1.1 Header<a id='1.1'></a>

image

@DevJonTaylor
Copy link

IDK if this hack will help anyone at all. However span tags are rendered in GitHub's Markdown Parse. The id attribute is replaced with id="user-content-${whatever you made the id}" I.E.

<span id="85af93540870"></span>
<!-- The above is rendered to the below -->
<span id="user-content-85af93540870"></span>

<!-- So when you do something like the below -->

* [Leading The Way](#85af93540870)

<!-- Filler Code Goes Here -->

## <span id="85af93540870"></span>Dude Where's My Car

It will link directly to the span.

This worked for me, I created a markdown creator that works off of six hex character ids which I utilized this hack to allow the table of contents to be generated.

Hope it helps someone!!! =)

Dev Jon Taylor,

  • Happy Coding!

@HelderMagalhaes
Copy link

So, characters like á,é,í,ó,ú,Á,É,Í,Ó,Ú,Ñ,ñ are just omitted in anchors.

According to the specification, an URL fragment is ASCII-only (no "international characters" accepted directly).
That applies to most other URL components. Browsers usually perform the interpretation automatically in the address bar in order to be more user friendly - copy+pasting into plain text (such as Notepad) allows to see the "real" URL.

@tillmannheigel
Copy link

Upd. You can use any id, its value does not have to match the text of the element.

# 1.1 [Header](#1.1)   

...some text...

# 1.1 Header<a id='1.1'></a>

Nice, that was actually the only real solution I found in the www for this issue. ❤️ Many thanks!

@yadimon
Copy link

yadimon commented Apr 13, 2022

Easiest Way I found to fix this was after writing down the headings on github, just do inspect element from the browser and find what the anchor links are 😁

thx, could not find the link for my complex text.

@AlexDev404
Copy link

Upd. You can use any id, its value does not have to match the text of the element.

# 1.1 [Header](#1.1)   

...some text...

# 1.1 Header<a id='1.1'></a>

Nice, that was actually the only real solution I found in the www for this issue. ❤️ Many thanks!

This works well. Thanks! 👍

@avinal
Copy link

avinal commented Jun 15, 2022

Thanks

@abhishp021
Copy link

abhishp021 commented Jul 1, 2022

Note- If anyone facing issues with anchor linking. Please ensure that the text of anchor and the text of place where you are linking are different.
For e.g. There will be problem if you use

> ### [Anchor Link](#anchor-link)
> ## Anchor Link

Here problem because "Anchor Link" is used as text in both lines
But if different text used in [ ] then no issues. For e.g. we added "1." in [ ]

> ### [1. Anchor Link](#anchor-link)
> ##  Anchor Link

@DiasFranciscoA
Copy link

DiasFranciscoA commented Sep 22, 2022

Is there a way to do the opposite don't generate anchor links. This seems to happen automatically in github wiki everytime you defined a header and that clutters the sidebar navigation.

@Harmyder
Copy link

Every time I change section name I need to go and update all the anchors.

@jdaw1
Copy link

jdaw1 commented Oct 22, 2022

Consider HTML <tr id="XXX">…. Then a link to #XXX is a link to that whole row. Clicking on a <a href="#XXX">to XXX</a> causes the whole row to be on the screen, if possible the top pixel of the row at the top of the screen (not always possible if row near end of page). This is good.

In Markdown, putting | <a name="XXX"></a> … |, and clicking on [to XXX](#XXX) jumps to the middle of the row, at least if there is an image in the row. The top half of the row isn’t visible: above top of viewport. This is not good.

Please, is there a known solution?

Jacks and Numbers
UnionJack One
UnionJack Two
UnionJack Three
UnionJack Four
UnionJack Five
UnionJack Six
UnionJack Seven
UnionJack Eight
UnionJack Nine
UnionJack Ten
UnionJack Eleven
UnionJack Twelve
UnionJack Thirteen
UnionJack Fourteen
UnionJack Fifteen
UnionJack Sixteen
UnionJack Seventeen
UnionJack Eighteen
UnionJack Nineteen
UnionJack Twenty
UnionJack TwentyOne
UnionJack TwentyTwo
UnionJack TwentyThree
UnionJack TwentyFour
UnionJack TwentyFive
UnionJack TwentySix
UnionJack TwentySeven
UnionJack TwentyEight
UnionJack TwentyNine
UnionJack Thirty
UnionJack ThirtyOne
UnionJack ThirtyTwo
UnionJack ThirtyThree
UnionJack ThirtyFour
UnionJack ThirtyFive
UnionJack ThirtySix

@jdaw1
Copy link

jdaw1 commented Oct 26, 2022

Solution found.
• The large image cannot be a link (which is what confounded me).
• Then wrap the <a names="…"></a> around the image.

@micmro
Copy link

micmro commented May 31, 2023

Just wanted to leave a note that this approach does have accessibility/semantic issues (ref: https://developers.google.com/style/headings-targets).

Unfortunately, Github does currently not support the extended markdown syntax heading-ids (e.g. ### My Heading {#my-heading-id}), so the most accessible approach would be to use the HTML equivalent <h3 id="my-heading-id">My Heading</h3> instead.

@Moonbase59
Copy link

Moonbase59 commented Apr 4, 2024

I needed a quick Markdown TOC generator that would be compatible with GitHub, so I made my own: gh-toc.

It’s basically a web page with some JavaScript: You paste in your Markdown and it generates a GitHub-compatible Table of Contents. Your browser does the work and nothing gets sent to the Internet.

Features:

  • Full Unicode support, all international characters.
  • Better handling of (hopefully) all underscore cases.
  • Correct handling of code with backticks ` inside.
  • Much better code block support (backticks, tildes, differing number of them).
  • YAML front matter support.
  • Optional output of the full Markdown file, ToC inserted between <!-- ToC begin --> and <!-- ToC end --> HTML comments, instead of just the ToC.
  • Optional named anchor generation for each ToC element (not needed for GitHub use).
  • Optional use of id instead name attribute in generated anchors.

Markdown test file included.

@k-Gillespie
Copy link

thank you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment