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:
![](/_next/image?url=https%3A%2F%2Ffirebasestorage.googleapis.com%2Fv0%2Fb%2Fyayo-code-blog-prod.appspot.com%2Fo%2Flocales%252Fen%252Fposts%252Fp7lHc8OgQ4gU0vVn8Tqc%252Fafca95b5-16a5-4419-b326-dec6b1439192.png%3Falt%3Dmedia%26token%3D03b61d31-f2cd-4bff-b1ed-22bb344ca85e&w=800&q=75)
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: "code"});
hljs.highlightAll();
</script>
The previous code must be added before the <head>
tag. Check the following image:
![](/_next/image?url=https%3A%2F%2Ffirebasestorage.googleapis.com%2Fv0%2Fb%2Fyayo-code-blog-prod.appspot.com%2Fo%2Flocales%252Fen%252Fposts%252Fp7lHc8OgQ4gU0vVn8Tqc%252F73f00c97-e538-48a6-a415-29a226f25d81.png%3Falt%3Dmedia%26token%3D29a34a2e-21b6-4cb0-a22e-322da1e459f6&w=800&q=75)
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:
![](/_next/image?url=https%3A%2F%2Ffirebasestorage.googleapis.com%2Fv0%2Fb%2Fyayo-code-blog-prod.appspot.com%2Fo%2Flocales%252Fen%252Fposts%252Fp7lHc8OgQ4gU0vVn8Tqc%252Fc0e2e48a-941f-49eb-8a0b-54672bb9fe51.png%3Falt%3Dmedia%26token%3D9f408ca4-6839-439c-bcda-f5d7338a8cb2&w=800&q=75)
That is all. Thanks for reading this article. I hope it can help you to improve your blogs.