How to Set and Change Heading Levels in Markdown
Write Markdown headings and subheadings with # or underline syntax, then raise or lower their levels without altering code blocks or other content.
In Markdown, the heading level comes from a marker at the start of a line or from an underline beneath it. This guide covers both syntaxes, how to write subheadings, and how to raise or lower heading levels, one at a time or across a whole document, without changing any other text.
What heading levels do to your text
A heading marker tells the renderer that a line is a heading and how deep it sits in the document's structure. When Markdown is converted to HTML, the six levels become the elements h1 through h6. Tables of contents, document outlines and screen-reader navigation are typically built from those elements, so the level changes how a document is organized and navigated, not just how it looks. Adjusting a level should therefore change only the marker. The heading's words and everything around it should stay the same.
Scope and evidence: the syntax rules below follow the CommonMark specification, which GitHub Flavored Markdown also builds on. Other Markdown flavors and older parsers can behave differently, so check the renderer you publish with. No tested evidence was available about specific editors, plugins or converters, so this guide does not compare or recommend particular products. It covers the syntax itself and generic text operations such as find-and-replace and a short script.
ATX headings: the hash-mark syntax
The most common form, called an ATX heading, starts a line with one to six hash characters (#). The number of hashes is the level. A space or tab must follow the hashes before the heading text.
# Level 1 heading
## Level 2 heading
### Level 3 heading
#### Level 4 heading
##### Level 5 heading
###### Level 6 heading
| Markdown marker | HTML element | Common convention |
| | h1 | Document or page title |
| | h2 | Main section |
| | h3 | Subheading within a section |
| | h4 | Subsection of a subheading |
| | h5 | Rarely needed nesting |
| | h6 | Deepest level available |
- A space (U+0020) or a tab must follow the hashes. In CommonMark, "#Heading" with no space is plain text, not a heading.
- Only one to six hashes count. Seven or more make the line an ordinary paragraph.
- Up to three leading spaces are allowed. Four or more spaces turn the line into an indented code block.
- You can add optional closing hashes ("## Title ##"). The renderer drops them, and they don't need to match the opening count.
- To start a line with a literal hash, escape it with a backslash: #.
# Heading <- level 1
#Heading <- plain text in CommonMark (no space after #)
## Heading <- level 2 (three leading spaces allowed)
## Heading <- indented code block (four leading spaces)
####### Heading <- plain text (seven hashes)
## Heading ## <- level 2; closing hashes are not shown
\# Heading <- literal text "# Heading"
The example above is illustrative. The arrows and notes on the right are explanations, not part of the Markdown.
Writing a subheading
A subheading is a heading one level deeper than the section it belongs to. Under a level 2 section, use ###. Under a level 3 subheading, use ####. Markdown lets you skip levels, for example jumping from ## straight to ####. However, outline tools and accessibility guidance generally expect levels to nest one step at a time. Many sites and static site generators render the page title as h1 from metadata. In those setups, the body usually starts at ##.
# Project Guide
## Installation
### Requirements
### Installing on Linux
#### Using a package manager
## Configuration
Setext headings: the underline syntax
When people search for a Markdown underline header, they usually mean the setext syntax. You write the heading text on one line and underline it on the next. Equals signs (=) make a level 1 heading and hyphens (-) make a level 2 heading. The underline can be any length. Setext headings only cover these two levels; there is no underline form for level 3 or deeper.
Document Title
==============
Section Title
-------------
- A line of hyphens directly under a paragraph makes that paragraph a level 2 heading, not a horizontal rule. If you want a horizontal rule (a thematic break), leave a blank line before the hyphens.
- In CommonMark, setext heading text can span several consecutive lines. Everything above the underline, back to the previous blank line, becomes the heading.
- Standard Markdown has no underline style for ordinary text. The underline syntax only creates headings.
Changing a single heading's level
- To demote an ATX heading (make it deeper), add one hash. To promote it, remove one hash. Keep the space after the hashes.
- To switch a setext heading between levels 1 and 2, replace the underline characters: = for level 1, - for level 2.
- To move a setext heading to level 3 or deeper, first convert it to ATX form, then set the number of hashes.
- Check the headings that follow. When you demote a section heading, its subheadings usually need to move down one level too so they stay nested below it.
Example of converting setext headings to ATX form, before and after:
Before:
User Guide
==========
Getting Started
---------------
After:
# User Guide
## Getting Started
Shifting every heading in a document
Bulk shifts come up when you paste one document into another. For example, the inserted file's # title has to become ## so it sits under the host document's title. A shift can also be needed when you split or merge files. Doing this by hand is error-prone, so most people use a regular-expression find-and-replace. A regular expression (regex) is a search pattern that matches text by its structure rather than by exact characters.
The patterns below use multiline mode, where ^ matches the start of each line. Editors write the replacement backreference differently: some use $1, others use \1. Each pattern includes the trailing space so that #hashtags and lines like #include are not matched. Before demoting, search for level 6 headings, because they cannot go deeper. Adding a seventh hash would turn them into plain paragraphs.
Demote one level (## becomes ###):
Find: ^(#{1,5})
Replace: #$1
Promote one level (### becomes ##; leaves # unchanged):
Find: ^#(#{1,5})
Replace: $1
(Each Find and Replace pattern ends with one space character.)
- Code blocks: a shell or Python comment such as "# install deps" inside a fenced code block matches the pattern and will be changed.
- Front matter: YAML comments at the top of a file look the same as headings to this pattern.
- Setext headings are not matched at all, so they keep their level while ATX headings around them move.
- Headings indented with one to three spaces are skipped, because the pattern requires the hash at the very start of the line.
- Headings written as raw HTML (such as <h2>) are not matched.
- Empty headings and headings with a tab after the hashes are missed, because the pattern requires a space.
To avoid the code-block problem, you can use a line-aware script that skips fenced code blocks. The Python sketch below is illustrative and has not been tested here. Run it on a copy of your file first.
import re
import sys
ATX = re.compile(r'^( {0,3})(#{1,6})(?=[ \t]|$)')
FENCE = re.compile(r'^ {0,3}(`{3,}|~{3,})')
def shift_headings(lines, delta):
out = []
fence = None
for line in lines:
m = FENCE.match(line)
if m:
marker = m.group(1)
if fence is None:
fence = marker
elif marker[0] == fence[0] and len(marker) >= len(fence):
fence = None
out.append(line)
continue
if fence is None:
h = ATX.match(line)
if h:
level = len(h.group(2)) + delta
if not 1 <= level <= 6:
sys.stderr.write('out of range, unchanged: ' + line)
else:
line = h.group(1) + '#' * level + line[h.end():]
out.append(line)
return out
if __name__ == '__main__':
delta = int(sys.argv[1])
lines = sys.stdin.read().splitlines(keepends=True)
sys.stdout.write(''.join(shift_headings(lines, delta)))
Usage example: python3 shift_headings.py 1 < input.md > output.md demotes every heading by one level, and -1 promotes. If a heading would move past level 1 or level 6, the script leaves it unchanged and prints a warning instead of merging two levels. Its limits: it ignores setext headings, indented code blocks, HTML blocks and YAML front matter, and it uses a simplified fence check that does not apply every CommonMark rule for closing fences.
Verifying the result
- Compare the original and edited files line by line. Only heading lines should differ.
- List the heading candidates in each version and check that the count is the same and every level moved by the intended amount.
- Look inside code blocks and front matter for comment lines that changed by mistake.
- Preview the rendered document or its outline, and confirm that no levels are skipped and that no sixth-level heading turned into plain text.
- Test links that point to headings. Many renderers build anchors from the heading text, so a level-only change normally leaves the text alone. If you also edited the wording, check those links.
diff original.md edited.md
grep -nE '^ {0,3}#{1,6}([ \t]|$)' edited.md
The grep command lists lines that look like ATX headings, with line numbers. It also lists matching comment lines inside code blocks, so review its output rather than treating the count as exact.
Markdown headings and HTML heading markup
Markdown headings are shorthand for HTML heading markup, and many renderers also accept raw HTML such as <h3>Title</h3> inside a Markdown file. Hash-based find-and-replace patterns and scripts do not see those tags, so documents that mix both forms need a separate pass for the HTML headings. Whether raw HTML is allowed at all depends on the renderer and its security settings.