How to format code snippets in blogger posts (2023)

If you want to show code snippets in your blog like this one:

var edad = 17;

  if (edad >= 18) {
    print('Es mayor de edad');
  } else {
    print('Es menor de edad');
  }

You can use highlight.js. To add it to your blog, you must edit the HTML:

Once you are inside the HTML editor, add the next lines of code:

<link href='https://unpkg.com/@highlightjs/cdn-assets@11.0.1/styles/default.min.css' rel='stylesheet'/>
<script src='https://unpkg.com/@highlightjs/cdn-assets@11.0.1/highlight.min.js'/>
<script>
hljs.configure({cssSelector: &quot;code&quot;});
hljs.highlightAll();
</script>

The previous code must be added before the <head> tag. Check the following image:

Now the code snippets that you want to highlight must be inside the tags <pre><code></code></pre>. If you want to write inline code snippets, use the tag <code></code>.

Example: The code at the beginning of this post has to be written like this::

<pre><code>
var edad = 17;
if (edad >= 18) {
	print('Es mayor de edad');
} else {
	print('Es menor de edad');
}
</code></pre>

It will look like this in the editor:

That is all. Thanks for reading this article. I hope it can help you to improve your blogs.

Share this article