Destiner's notes

Code Highlighting in Astro

23 February 2022

There are generally 2 ways to write code snippets in Astro. The first way is to use code fences (``` syntax). The second way is to use the <Code> component.

While using the Code component might be useful in some contexts (e.g. inside an .astro file), Personally, I find it a bit alienating inside a Markdown file. So this guide will mostly focus on the Markdown code fences.

Inline code

Inline code is rendered as a direct children of a paragraph. To style inline code snippets, use p > code selector. Here’s an example:

css
p > code {
padding: 4px;
border-radius: 4px;
background: #343434;
font-family: Consolas, Monaco, 'Andale Mono', monospace;
direction: ltr;
font-size: 14px;
}

Block code

Blocks of code are rendered inside the pre element. Use pre > code as a selector:

css
article pre {
padding: 8px 16px;
overflow: auto;
border-radius: 4px;
background: #343434;
}
pre > code {
border-radius: 4px;
background: #bbb;
font-family: Consolas, Monaco, 'Andale Mono', monospace;
display: block;
font-size: 14px;
line-height: 1.5;
word-break: normal;
white-space: pre;
word-spacing: normal;
tab-size: 4;
}

Style deduplication

As you may notice, both of these rules are pretty much identical. If you want to have the consistent styling of both inline and block snippets, you can unify those rules:

css
pre {
padding: 8px 16px;
overflow: auto;
border-radius: 4px;
background: #343434;
}
code {
padding: 4px;
border-radius: 4px;
background: #343434;
font-family: Consolas, Monaco, 'Andale Mono', monospace;
direction: ltr;
font-size: 14px;
}
pre > code {
padding: 0;
line-height: 1.5;
word-break: normal;
white-space: pre;
word-spacing: normal;
tab-size: 4;
}

Syntax highlighting

By default, Markdown code blocks are processed by Prism, but <Code> blocks are highlighted by Shiki.

Prism

By default, Prism will only split your code snippets into tokens, but it won’t style them. To provide a highlighting, you need to provide a stylesheet with a proper theme. You can create a stylesheet on the Prism website. Select the theme, choose languages, and click “Download CSS” at the bottom of the page. Add the downloaded stylesheet to your site. You can also tweak the stylesheet to better match the style of your site.

Shiki

It’s possible to use Shiki to highlight the Markdown code blocks. To do this, set syntaxHighlight option in the Astro config. Here, you can also provide options such as the theme and the list of supported languages:

js
import { defineConfig } from 'astro/config';
export default defineConfig({
markdown: {
render: [
'@astrojs/markdown-remark',
{
syntaxHighlight: 'shiki',
shikiConfig: {
theme: 'nord',
langs: ['js', 'html', 'css', 'astro'],
wrap: false,
},
},
],
},
});