Displaying code effectively in your Blogger blog posts is crucial for sharing technical tutorials, demonstrating programming concepts, or showcasing your coding skills. A well-formatted "script box" or "code block" not only improves readability but also makes your content more engaging for your audience. This guide will walk you through various methods of creating script boxes in Blogger, from basic HTML to syntax highlighting and best practices.
Why Use Code Blocks (Script Boxes) in Blogger?
Code blocks offer several key benefits:
- Enhanced Readability: They visually separate code from regular text.
- Formatting Preservation: They preserve indentation and line breaks.
- Improved Comprehension: Syntax highlighting makes code easier to understand.
- Professional Presentation: They give your blog posts a polished look.
Methods for Creating Code Blocks in Blogger
1. Basic HTML with <pre>
and <code>
Tags
The simplest method is using the <pre>
(preformatted text) and <code>
(code) HTML tags directly in your Blogger post editor (HTML view).
function myFunction() {
console.log("Hello, Blogger!");
}
<pre>
preserves whitespace and line breaks. <code>
indicates the enclosed text is code.
Limitations: This provides basic formatting but lacks syntax highlighting.
2. Syntax Highlighting with Highlight.js (Recommended)
For a professional look, use Highlight.js. The best approach is to include the Highlight.js files *per post*:
-
In your Blogger Post (HTML View): Add the following code snippet *at the beginning* of your post's 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>
-
Use the following structure for your code blocks:
function myFunction() { console.log("Hello, Highlight.js!"); }
Replace
language-javascript
with the correct language class (e.g.,language-python
,language-html
,language-css
). See the Highlight.js documentation for supported languages.
Why per-post is better: Avoids theme conflicts and offers more flexibility.
Best Practices for Code Blocks in Blogger
- Monospace Font: Use a monospace font for code.
- Escape Special Characters: Escape
<
,>
, and&
as needed. - Line Numbers (Optional): Use line numbers if helpful (check Highlight.js docs).
- Keep Code Concise: Break down long code blocks.
- Test Your Code: Ensure your code works correctly.
- Descriptive Language Classes: Use correct language classes for syntax highlighting.
- Highlight.js Theme Customization: Choose a theme you like.
Example with HTML and JavaScript
<div id="myDiv">This is some HTML</div>
<script>
document.getElementById("myDiv").innerHTML = "Hello from JavaScript!";
</script>
By following these methods and best practices, you can create professional-looking code blocks in your Blogger blog posts.