Skip to content

Instantly share code, notes, and snippets.

@TobiasPalludan
Last active June 7, 2024 15:27
Show Gist options
  • Save TobiasPalludan/5948533e97d260a04ea47e44ea7cc6b0 to your computer and use it in GitHub Desktop.
Save TobiasPalludan/5948533e97d260a04ea47e44ea7cc6b0 to your computer and use it in GitHub Desktop.
Same-file anchors and cross-file anchors in Github Markdown,

Same-file anchors for Github

Making an anchor to another heading in the same file as the anchor is straightforward.

[The header of this page](#same-file-anchors-for-github)

Will show as The header of this page.

The heading should be downcased, spaces changed to hyphens, and removed anything not a letter, hyphen, or space. If this id is not unique, you add "-1", "-2", and so forth to the header.

Examples: # Some HEADER Becomes (#some-header)

# New-header2 Becomes (#new-header)

Cross-file anchors for Github

Caution

Read comment by @karlhorky as this method currently doesn't work

If you are working with Github Pages and want to make a header to another file you simply add filename.md in front of the header's link. So if we had to reference a file in the same directory named github-tips.md with a header called # Anchors we would simply write (github-tips.md#anchors).

Like with a normal command-line folder navigation, you can use / go into a folder and ../ to go out of a folder.

See the following example:

.
├── folder 1
│   ├── first.md
│   ├── second
│   │   └── fileInSecond.md
│   └── main.md
└── outer.md

Placing links inside main.md will look like:

[first](first.md)

[file in folder](second/fileInSecond.md)

[outer](../outer.md)

Thanks

These links inspired this Gist, and will also provide in-depth information, hopefully answering any further questions.

Thanks to @asabaylus and @TomOnTime for the same-file anchors. Thanks to @uranusjr for the cross-file anchors.

@karlhorky
Copy link

karlhorky commented Mar 30, 2023

This "Cross-file anchors" solution doesn't currently work on GitHub (Mar 2023) with a relative file link in the same repo (eg. ./windows.md#user-content-xxx). Probably another bug in GitHub's client-side router, but I guess probably won't be fixed anytime soon.

Workaround

Link to the full GitHub URL with a www. subdomain - this will cause a redirect to the non-www. version, and respect the anchor:

-[Expo + React Native](./windows.md#user-content-expo-react-native)
+[Expo + React Native](https://www.github.com/upleveled/system-setup/blob/main/windows.md#user-content-expo-react-native)

@zz-james
Copy link

zz-james commented Apr 9, 2024

👍

@signalogic
Copy link

@karlhorky, yes this works. The full URL is needed - even without "www" it will fail. Dang I spent 3 hours on this searching stackoverflow, etc before finally searching on "Github markdown scroll to anchor" and finding your fix

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