Sharing code snippets effectively is essential for any technical blogger. In Blogger, "script boxes" (or code blocks) are the key to presenting your code clearly and professionally. This guide provides a comprehensive walkthrough, from basic HTML to advanced syntax highlighting, all without touching your theme's code!
Why Use Code Blocks?
Code blocks offer numerous benefits:
- Enhanced Readability: They visually separate code from text.
- Formatting Preservation: They maintain indentation and line breaks.
- Improved Comprehension: Syntax highlighting color-codes code elements.
- Professional Look: Well-formatted code blocks elevate your blog's credibility.
Method 1: The Foundation - HTML <pre>
and <code>
The simplest approach uses HTML's <pre>
(preformatted text) and <code>
(code) tags:
function myFunction() {
console.log("Hello, Blogger!");
}
<pre>
preserves formatting, while <code>
signifies code.
Limitations: Basic formatting, no syntax highlighting.
Method 2: Shine with Syntax Highlighting (Recommended)
For polished code, use Highlight.js. The per-post method is best:
-
1. Add Highlight.js to Your Post
In your Blogger post (HTML view): Add this at the start of your content:
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/styles/default.min.css"> <script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/highlight.min.js"></script> <script>hljs.highlightAll();</script>
-
2. Use the Correct HTML for Your Code
Use this structure for your code:
// Your JavaScript code here function myFunction() { console.log("Hello, Highlight.js!"); }
Replace
language-javascript
with the correct language class (e.g.,language-python
,language-html
). See the Highlight.js docs.
Why Per-Post is Best: No theme edits, more flexibility, fewer conflicts.
Best Practices
- Monospace Font: Essential for code clarity.
- Escape Special Characters: Use
<
,>
,&
for<
,>
,&
. - Line Numbers (Optional): Check Highlight.js docs.
- Keep Code Concise: Break down long blocks.
- Test Your Code: Always verify it works.
- Descriptive Language Classes: Critical for Highlight.js.
- Highlight.js Themes: Customize the look.
Example (HTML & JavaScript):
<div id="myDiv">This is HTML</div>
<script>
document.getElementById("myDiv").textContent = "Hello!";
</script>
Conclusion
Mastering code blocks elevates your Blogger content. Highlight.js (per-post) is the most effective way to showcase your code beautifully.