Code formatting on Medium is easy. There are three main ways you can use to format code on Medium:
- Inline code for small inline expressions.
- Code blocks for larger chunks of code without syntax highlighting.
- Github gists for larger chunks of code with syntax highlighting.
How to Write Inline Code
To format code inside a paragraph inline like this: <h1>Hello</h1>
, simply highlight the code and press the backtick (`) key.
Here is an illustration:
Notice how inline code cannot be used in headings, quotes, or image captions.
How to Create a Bigger Code Block
If inline code is not enough for your purposes, you can also create a bigger block of code:
while(1 < 2) {
print("Hello, world!")
}
To create a block of code, press one of these key combinations depending on your system:
- Windows: ctrl+alt+6
- Mac: command+option+6
- Linux: ctrl+alt+6
OR type three backticks (“`) in a new line to start a new code block and start typing code.
Tip: If you’re copy-pasting code from an editor to Medium, you may lose code formatting. To fix this, use the Paste and Match Style property by right-clicking the code block when pasting:
Github Gists
This is a common way to add chunks of code to your story.
Embedding your code as a Github Gist preserves the code style e.g. syntax highlighting, indentations, etc:
This is an example.js file embedded in Medium as a GitHub Gist
Furthermore, if you need to make changes to the code in the gist, the changes will automatically be reflected in the article.
Also, some publications accept programming articles only if Github Gists are used when embedding code.
How to create a GitHub Gist:
- Go to https://gist.github.com/
- Give the gist a description, write the code, and remember to use the proper file extension. e.g. with javascript, name your gist like
example.js
- When you’re ready, publish the gist by creating a public gist.
4. Copy the URL of the published gist and embed it into Medium:
Conclusion
Today you learned how to format code on Medium in three common ways:
- Inline code.
- Code blocks
- Github gists.
I hope you find these code formatting tips useful.