A tutorial on using Pandoc to convert Markdown to HTML using a CSS stylesheet and a custom template.
Using Pandoc, you can convert a Markdown file to HTML using the command:
pandoc -s sample.md -o sample.html
If you have CSS styles defined in a file, you can apply
that using the -c
option:
pandoc -s sample.md -c custom.css -o sample.html
Classless CSS styles
If you do not have a custom stylesheet, you can consider using classless 1 CSS styles like Sakura, Water, MVP, or others.
Download the respective .css
file and use it in the command above in place of custom.css
. Then, check if the HTML output looks as you expect.
If not, you will need to make some changes to Pandoc’s default HTML template. 2 Follow the steps below to do this.
Customize HTML template
As an example, I will customize Pandoc’s default HTML template to make use of the MVP.css stylesheet.
Note: You can get all files discussed below from this repository
Step 1. Get default template
First, save Pandoc’s default HTML template to a file:
pandoc -D html > template.html
Step 2. Update template
Make changes in template.html
as necessary.
To include mvp.css
, I made these changes in the template:
- Move TOC to a dropdown menu in site navigation
- Add a button with a link
- Some minor CSS style adjustments
Step 3. Use the modified template
Run pandoc
again with the modified template and CSS file to generate the final output:
pandoc -s sample.md -c css/mvp.css \
--template template.html --toc \
--toc-depth=2 -o sample.html
Screenshot of sample.html, before and after:
Download files
Download this template along with all required files from this repository.
Note: I have added YAML metadata in
sample.md
. Pandoc will use these values for the corresponding fields in the template. You can also provide them as options in thepandoc
command.
Blog post updates
-
2023-11-25
Fix links. Minor updates to text. -
2023-07-21
Changed post title.
-
Applies styles to HTML elements directly. No need to define classes. ↩
-
Pandoc’s documentation on templates ↩
Comments