1211

I am writing a large Markdown document and would like to place a table of contents of sorts at the beginning that will provide links to various locations in the document. How can I do this?

I tried using:

[a link](# MyTitle)

where MyTitle is a title within the document but this didn't work.

3

17 Answers 17

1989

Github automatically parses anchor tags out of your headers. So you can do the following:

[Custom foo description](#foo)

# Foo

In the above case, the Foo header has generated an anchor tag with the name foo

Note: just one # for all heading sizes, no space between # and anchor name, anchor tag names must be lowercase, and delimited by dashes if multi-word.

[click on this link](#my-multi-word-header)

### My Multi Word Header

Update

Works out of the box with pandoc too.

21
  • 167
    If your header contains multiple words, "Like this one", replace spaces with hyphens in the anchor [just](#like-this-one).
    – Mogsdad
    Feb 4, 2016 at 21:51
  • 6
    Does this only work for H1 headers? If linking to a H2 header (i.e. ## Foo), do I also need to put two number signs in the link, i.e. [Foo](##foo)? I cannot get your syntax or mine to work (with the extra number sign).
    – GrayedFox
    Oct 12, 2016 at 14:08
  • 16
    @GrayedFox, if you want to create a link for ab H2 header ## Foo, try [this is my link to Foo](#foo) ... that is: single hash, no space between hash and lowercase-kebab-case-name-of-header
    – Abdull
    Oct 25, 2016 at 12:01
  • 12
    As a tip: check out the anchor that is displayed next to your header on Github to obtain the respective link, i.e. if it contains special characters, they are automatically removed and the correct link is shown there. Jul 13, 2017 at 3:58
  • 8
    What about when the headings have number ? # 3. Third point [Third point](#3.-third.point) doesn't work
    – Aditya
    Nov 10, 2017 at 3:15
234

This may be out-of-date thread but to create inner document links in markdown in Github use...
(NOTE: lowercase #title)

# Contents
 - [Specification](#specification) 
 - [Dependencies Title](#dependencies-title) 

## Specification
Example text blah. Example text blah. Example text blah. Example text blah. 
Example text blah. Example text blah. Example text blah. Example text blah. 
Example text blah. Example text blah. Example text blah. Example text blah. 
Example text blah. Example text blah. 

## Dependencies Title
Example text blah. Example text blah. Example text blah. Example text blah. 
Example text blah. Example text blah. Example text blah. Example text blah. 
Example text blah. Example text blah. Example text blah. Example text blah. 
Example text blah. Example text blah. 

A good question was made so I have edited my answer;

An inner link can be made to any title size using - #, ##, ###, #### I created a quick example below... https://github.com/aogilvie/markdownLinkTest

6
  • 2
    In your example, the link tags only have one #, but the headers that they are supposed to link to have two ##; shouldn't they be the same? Feb 24, 2014 at 18:55
  • 7
    Good question. The answer is no. the # in (#dependencies-title) tells Github markdown this is an inner link. The text that follows can be any title size. Here is an example test I made...https://github.com/aogilvie/markdownLinkTest
    – Ally
    Feb 27, 2014 at 2:06
  • 2
    Does that depend on the flavor of markdown? It seems like it works fine in the markdown editor, but when I save to html or pdf the ids dont get added to the appropriate tags. I'd be fine just dumping an anchor in there, but it seems like your method is so much cleaner and faster. Apr 8, 2014 at 20:18
  • This may be correct in Github’s markdown implementation but it is not supported in plain markdown (as defined by the specification daringfireball.net/projects/markdown/syntax#html). In that spec there is no anchor created automatically by a header so the explicit anchor is the only guaranteed solution that will work everywhere. Feb 3, 2021 at 9:11
  • 1
    In Boostnote, it's case sensitive. - [Specification](#Specification) - [Dependencies Title](#Dependencies-Title)
    – galian
    Jun 3, 2021 at 10:48
165

Experimenting, I found a solution using <div…/> but an obvious solution is to place your own anchor point in the page wherever you like, thus:

<a name="abcde">

before and

</a>

after the line you want to "link" to. Then a markdown link like:

[link text](#abcde)

anywhere in the document takes you there.

The <div…/> solution inserts a "dummy" division just to add the id property, and this is potentially disruptive to the page structure, but the <a name="abcde"/> solution ought to be quite innocuous.

(PS: It might be OK to put the anchor in the line you wish to link to, as follows:

## <a name="head1">Heading One</a>

but this depends on how Markdown treats this. I note, for example, the Stack Overflow answer formatter is happy with this!)

18
  • 2
    If you do this you should be aware that the div strips other markdown formatting, such as ## headers.
    – 2rs2ts
    Jul 4, 2011 at 16:47
  • @user691859 Can you elaborate? Perhaps we can update an answer to make it work better. I saw TextMate suppress highlighting, until I indented the div, but no problem with the processed markdown viewed from a browser. Jul 5, 2011 at 15:55
  • In WriteMonkey I found that if I precede any text with the <div/> several lines below are affected. Instead I have to wrap the text I am linking in a full div tag clause and I have to RE-SPECIFY the behavior from scratch using real HTML. Boo.
    – 2rs2ts
    Jul 6, 2011 at 17:28
  • 7
    This works well, thanks. For anyone wondering, this also works with GitHub-hosted-and-displayed Markdown files.
    – Alex Dean
    Mar 5, 2012 at 15:52
  • 6
    To be forward-compatible with HTML5, I would like to recommend replacing <a name="head1"/> with <a id="head1"/>.
    – binki
    Oct 22, 2013 at 19:17
43

yes, markdown does do this but you need to specify the name anchor <a name='xyx'>.

a full example,

this creates the link
[tasks](#tasks)

elsewhere in the document, you create the named anchor (whatever it is called).

<a name="tasks">
   my tasks
</a>

note that you could also wrap it around the header too.

<a name="tasks">
### Agile tasks (created by developer)
</a>
3
  • I tried it. It doesn't work. <a> creates a link to nowhere Sep 21, 2021 at 9:11
  • @KansaiRobot It doesn't create a link; it creates an anchor which can be the target of a link. You have to write a link to get to it. Also you have to name the anchor so you can refer to it by name in the link. Sep 22, 2021 at 17:15
  • It's just a shallow duplicate of already answered. What is the difference?
    – hc_dev
    Jun 25, 2022 at 18:07
35

In pandoc, if you use the option --toc in producing html, a table of contents will be produced with links to the sections, and back to the table of contents from the section headings. It is similar with the other formats pandoc writes, like LaTeX, rtf, rst, etc. So with the command

pandoc --toc happiness.txt -o happiness.html

this bit of markdown:

% True Happiness

Introduction
------------

Many have posed the question of true happiness.  In this blog post we propose to
solve it.

First Attempts
--------------

The earliest attempts at attaining true happiness of course aimed at pleasure. 
Soon, though, the downside of pleasure was revealed.

will yield this as the body of the html:

<h1 class="title">
    True Happiness
</h1>
<div id="TOC">
    <ul>
        <li>
            <a href="#introduction">Introduction</a>
        </li>
        <li>
            <a href="#first-attempts">First Attempts</a>
        </li>
    </ul>
</div>
<div id="introduction">
    <h2>
        <a href="#TOC">Introduction</a>
    </h2>
    <p>
        Many have posed the question of true happiness. In this blog post we propose to solve it.
    </p>
</div>
<div id="first-attempts">
    <h2>
        <a href="#TOC">First Attempts</a>
    </h2>
    <p>
        The earliest attempts at attaining true happiness of course aimed at pleasure. Soon, though, the downside of pleasure was revealed.
    </p>
</div>
7
  • 1
    Thanks, this was exactly what I needed. I was using Textmate to convert Markdown to HTML, will switch to pandoc. May 13, 2010 at 3:08
  • 1
    You might give the demo Pandoc tmbundle up on Github a try (there's also emacs pandoc-mode, etc.) The tmbundle re-uses the MultiMarkdown-specific syntax highlighter, so there are a (very) few oddities. Also, a lot of the associated scripts are highly customized -- e.g. Context, not LaTeX etc. -- but the idea is that the users will alter them as they please, which I found pretty simple. It should probably be git clone -ed into the lowest or outermost tmbundle directory, ~/Library/Application\ Support/TextMate/Bundles to simplify integration. May 14, 2010 at 13:11
  • I wonder what pandoc does in the case of two headings with the same name? Jun 29, 2011 at 10:29
  • 2
    It adds -1 to the first repetition of the id, -2 to the second, etc. Jun 29, 2011 at 21:34
  • 8
    I found that I had to add the --standalone option to the pandoc command to get it to actually output the table of contents itself in the output. Without that switch, it would make the headers into links back to the #toc named anchor, but not actually output the named anchor and list of like itself. May 10, 2012 at 18:43
29

Just follow the [text](#link) syntax and follow these guidelines:

  • write the letters (lowercase) and numbers as they are
  • replace spaces with dashes -
  • remove the rest of the characters

So for example if you have these sections:

# 1. Python

# 2. c++

# 3. c++11

# 4. asp.net-core

You can add a reference by using:

[1. Python](#1-python)
[2. c++](#2-c)
[3. c++11](#3-c11)
[4. asp.net-core](#4-aspnet-core)

Note how asp.net-core becomes aspnet-core, 1. python becomes 1-python, etc.

27

The pandoc manual explains how to link to your headers, using their identifier. I did not check support of this by other parsers, but it was reported that it does not work on github.

The identifier can be specified manually:

## my heading text {#mht}

Some normal text here,
including a [link to the header](#mht).

or you can use the auto-generated identifier (in this case #my-heading-text). Both are explained in detail in the pandoc manual.

NOTE: This only works when converting to HTML, LaTex, ConTeXt, Textile or AsciiDoc.

0
22

Universal solutions

This question seems to have a different answer according to the markdown implementation.
In fact, the official Markdown documentation is silent on this topic.
In such cases, and if you want a portable solution, you could use HTML.

Before any header, or in the same header line, define an ID using some HTML tag.
For example: <a id="Chapter1"></a>
You will see this in your code but not in the rendered document.

Full example:

See a full example (online and editable) here.

## Content

* [Chapter 1](#Chapter1)
* [Chapter 2](#Chapter2)

<div id="Chapter1"></div>
## Chapter 1

Some text here.  
Some text here.
Some text here.

## Chapter 2 <span id="Chapter2"><span>

Some text here.  
Some text here.
Some text here.

To test this example, you must add some extra space between the content list and the first chapter or reduce the window height.
Also, do not use spaces in the name of the ids.

5
  • Uh..., seemed nice. Tried it, two problems: (1). ## Chapter 1 needs an open line above it. (2). The link does not work... Mar 5, 2020 at 8:12
  • 1
    Ah, it doesn't work in intellij markdown plugin I used; but DOES work in Macdown markup editor. Mar 5, 2020 at 8:25
  • Still, tested on github: open line above the header is required, but it works. Mar 5, 2020 at 9:08
  • @musicformellons can you please try without the opening line but properly closing the span tag?<br> <span id="Chapter1"><span>
    – ePi272314
    Mar 5, 2020 at 14:53
  • For me in GitHub works only the approach with the empty line between <div... and the section ##
    – dadhi
    Jun 5, 2020 at 11:20
12

Some additional things to keep in mind if ya ever get fancy with symbols within headings that ya want to navigate to...

# What this is about


------


#### Table of Contents


- [About](#what-this-is-about)

- [&#9889; Sunopsis](#9889-tldr)

- [:gear: Grinders](#it-grinds-my-gears)

- [Attribution]


------


## &#9889; TLDR


Words for those short on time or attention.


___


## It Grinds my :gear:s


Here _`:gear:`_ is not something like &#9881; or &#9965;


___


## &#9956; Attribution


Probably to much time at a keyboard



[Attribution]: #9956-attribution

... things like #, ;, &, and : within heading strings are generally are ignored/striped instead of escaped, and one can also use citation style links to make quick use easier.

Notes

GitHub supports the :word: syntax in commits, readme files, etc. see gist(from rxaviers) if using'em is of interest there.

And for just about everywhere else decimal or hexadecimal can be used for modern browsers; the cheat-sheet from w3schools is purdy handy, especially if using CSS ::before or ::after pseudo-elements with symbols is more your style.

Bonus Points?

Just in case someone was wondering how images and other links within a heading is parsed into an id...

- [Imaged](#alt-textbadge__examplehttpsexamplecom-to-somewhere)


## [![Alt Text][badge__example]](https://example.com) To Somewhere


[badge__example]:
  https://img.shields.io/badge/Left-Right-success.svg?labelColor=brown&logo=stackexchange
  "Eeak a mouse!"

Caveats

MarkDown rendering differs from place to place, so things like...

## methodName([options]) => <code>Promise</code>

... on GitHub will have an element with id such as...

id="methodnameoptions--promise"

... where as vanilla sanitation would result in an id of...

id="methodnameoptions-codepromisecode"

... meaning that writing or compiling MarkDown files from templates either requires targeting one way of slugifeing, or adding configurations and scripted logic for the various clever ways that places like to clean the heading's text.

7

There is no such directive in the Markdown spec. Sorry.

3
  • Uh oh! Do you know if MultiMarkdown or Textile support it? I was thinking of migrating to MD for all my documentation but this a deal breaker. Thanks for the help! May 12, 2010 at 22:38
  • 5
    What do you mean by "directive"? Other solutions to exactly the problem have been posted here. Jan 23, 2016 at 21:00
  • The markdown spec explicitly allows html tags, so this is allowed. And it works. At least last time I tried it. Dec 18, 2020 at 19:54
6

Gitlab uses GitLab Flavored Markdown (GFM)

Here "all Markdown-rendered headers automatically get IDs"

One can use mouse to :

  • move mouse over header
  • move mouse over hover selector which becoms visible to the left from header
  • copy and save link using right mouse click

    For example in README.md file I have header:

## series expansion formula of the Boettcher function

which gives a link :

https://gitlab.com/adammajewski/parameter_external_angle/blob/master/README.md#series-expansion-formula-of-the-boettcher-function

Prefix can be removed so the link here is simply

file#header

which here means:

README.md#series-expansion-formula-of-the-boettcher-function

Now it can be used as :

[series expansion formula of the Boettcher function](README.md#series-expansion-formula-of-the-boettcher-function)

One can also do it manually: replace spaces with hyphen sign.

Live example is here

1
  • The file is anticipated automatically, you don't need to specify it. [series expansion formula of the Boettcher function](#series-expansion-formula-of-the-boettcher-function) should do the trick.
    – magic_al
    Oct 26, 2021 at 6:58
2

In addition to the above answers,

When setting the option number_sections: true in the YAML header:

number_sections: TRUE

RMarkdown will autonumber your sections.

To reference those autonumbered sections simply put the following in your R Markdown file:

[My Section]

Where My Section is the name of the section

This seems to work regardless of the section level:

# My section

## My section

### My section

2

This works for me:

Longer example with GitHub preview here: https://gist.github.com/manero6/a0a67e8f9ebd7028f6fae51c49208b5d

# Title
title blablabla

#### Table of Content

- [First](#first)
- [Second](#second)
- [Third](#third-ᵗᵒᵖ)
- [Fourth](#fourth-)
- [Fifth](#-fifth)

## [First][toc]
1st

## [Second][toc]
2nd

## Third [ᵗᵒᵖ][toc]
3rd

## Fourth [^][toc]
4th

## [^][toc] Fifth
5th

[toc]: #table-of-content "go to Table of Content"
1

Using kramdown, it seems like this works well:

[I want this to link to foo](#foo)
....
....
{: id="foo"}
### Foo are you?

I see it's been mentioned that

[foo][#foo]
....
#Foo

works efficiently, but the former might be a good alternative for elements besides headers or else headers with multiple words.

1

Since MultiMarkdown was mentioned as an option in comments.

In MultiMarkdown the syntax for an internal link is simple.

For any heading in the document simply give the heading name in this format [heading][] to create an internal link.

Read more here: MultiMarkdown-5 Cross-references.

Cross-References

An oft-requested feature was the ability to have Markdown automatically handle within-document links as easily as it handled external links. To this aim, I added the ability to interpret [Some Text][] as a cross-link, if a header named “Some Text” exists.

As an example, [Metadata][] will take you to # Metadata (or any of ## Metadata, ### Metadata, #### Metadata, ##### Metadata, ###### Metadata).

Alternatively, you can include an optional label of your choosing to help disambiguate cases where multiple headers have the same title:

### Overview [MultiMarkdownOverview] ##

This allows you to use [MultiMarkdownOverview] to refer to this section specifically, and not another section named Overview. This works with atx- or settext-style headers.

If you have already defined an anchor using the same id that is used by a header, then the defined anchor takes precedence.

In addition to headers within the document, you can provide labels for images and tables which can then be used for cross-references as well.

1
  • This is true for Multimarkdown; the explicit anchor method <a> should work in any Markdown document. Furthermore you can put an anchor anywhere in the document body, not just in headings, images or tables. Sep 22, 2021 at 17:21
1

Some more spins on the <a name=""> trick:

<a id="a-link"></a> Title
------

#### <a id="a-link"></a> Title (when you wanna control the h{N} with #'s)
1

In my case I was looking for a TOC solution without Pandoc. Each TOC entry contains a link to a header in the format [Display Name](#-url-formatted-name-of-header)

For the simple case of 2 indent levels,

1. [Installation](#1-installation)  
1.1. [Minimum System Requirements](#11-minimum-system-requirements)  
1.2. [Prerequisites](#12-prerequisites)  

Results in:

  1. Installation
    1.1. Minimum System Requirements
    1.2. Prerequisites

For general multi-level numbered lists containing 3 or more indent levels, the list fails to indent further at levels 3 or higher (such as 1.3.2.). Instead the best solution I could find is using >>> to format with nested blockquotes.

## Table of Contents  
>1. [Installation](#1-installation)  
>>1.1. [Minimum System Requirements](#11-minimum-system-requirements)  
>>1.2. [Prerequisites](#12-prerequisites)  
>>>1.2.1. [Preparation of Database Server](#121-preparation-of-database-server)  
>>>1.2.2. [Preparation of Other Servers](#122-preparation-of-other-servers)  
>>  
>>1.3. [Installing – Single Server](#13-installing-single-server)  
>>1.4. [Installing – Multi Server](#14-installing-multi-server)  
>>>1.4.1. [Database Server](#141-database-server)  
>>>...  

Results in a nicely rendered TOC on GitHub. Can't render it here without SO's linter complaining about unformatted code.

Note the blank entry after 1.2.2.
Without the blank entry your following lines remain stuck at the 3rd blockquote indent level.

Contrast that with bulleted lists which "just work" using only spaces or tabs as indent markers -

## Table of Contents  
- [Installation](#1-installation)  
  - [Minimum System Requirements](#11-minimum-system-requirements)  
  - [Prerequisites](#12-prerequisites)  
    - [Preparation of Database Server](#121-preparation-of-database-server)  
    - [Preparation of Other Servers](#122-preparation-of-other-servers)  
  - [Installing – Single Server](#13-installing-single-server)  
  - [Installing – Multi Server](#-installing-multi-server)  
    - [Database Server](#141-database-server)  
    - ...  

Results in:

Table of Contents

  • Installation
    • Minimum System Requirements
    • Prerequisites
      • Preparation of Database Server
      • Preparation of Other Servers
    • Installing – Single Server
    • Installing – Multi Server
      • Database Server
      • ...

All above indented lists would successfully link to the following headers in GitHub markdown (headers fail to link in SO-flavored markdown for some reason) -

# 1. Installation  
## 1.1. Minimum System Requirements  
## 1.2. Prerequisites  
### 1.2.1. Preparation of Database Server  
### 1.2.2. Preparation of Other Servers  
## 1.3. Installing – Single Server  
## 1.4. Installing – Multi Server   
### 1.4.1. Database Server 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.