Markdown Guide — Part 6: Writing Code in Markdown
1. Inline Code
When you need to highlight a command, variable name, or a short piece of code within text, use inline code.
Markdown wraps code with single backticks `.
Example:
In Python, you can print text using `print("Hello, world!")`.
Result:
In Python, you can print text using print("Hello, world!").
Best Practices:
- Use inline code only for short snippets, not multi-line examples;
- Avoid adding extra spaces inside backticks.
2. Code Block
For multi-line code examples, configuration files, or function demonstrations, use code blocks.
There are two ways to create code blocks:
Using triple backticks (recommended)
Add three backticks ``` before and after the code.
Example:
```python
def greet(name):
print(f"Hello, {name}!")
```
Result:
def greet(name):
print(f"Hello, {name}!")
Using indentation (legacy syntax)
Adding four spaces or a tab before each line can also create a code block, but this method is less flexible than using backticks.
function sayHello() {
console.log("Hello!");
}
3. Syntax Highlighting
You can enable syntax highlighting by writing the language name after the opening triple backticks.
For example: ```javascript.
Example:
const fruits = ["apple", "banana", "orange"];
fruits.forEach(fruit => console.log(fruit));
Best Practices:
- Always specify the language (e.g.,
python,java,html); - Use lowercase for language names;
- Avoid mixing multiple languages in one block.
4. Escaping Backticks
If your code contains backticks, wrap it with multiple layers of backticks to prevent conflicts.
Example:
````markdown Example: `` `code inside code` ``. ````
Result:
Example: `` `code inside code` ``.
