A CSS style to post code in your blog

So, you own a blog and you'd like to post some code. Is it HTML, CSS, PHP, Java, ...? You need to highlight and format it, somehow. For example, here is the code to enumerate an associative array in PHP:

echo " Array $arr:<br>\n";
foreach ($arr as $key => $value) {
echo " - Key: $key -&gt; $value<br>\n";

First of all you need a parser to highlight the code. Most of good editors (e.g. Kate, SciTE) have an "export as HTML" feature, and that's what you need. After exporting the code to HTML, you need to format the paragraph some how in a way you like (tipically with a monospaced font, and often with a special background color). Another good thing would be a horizontal scrollbar appearing only when needed, without the normal word-wrap which is a bit invasive for code quotes.
If you like the CSS style of the above paragraph, I can avoid you the effort to look for it in the source of this page; here's the exact same CSS I use in this blog (I just added some :hover border change):

 /* CSS for code quotes by http://binaryunit.blogspot.com
by Eugenio Rustico */
width: 60%;
background: #EEE;
border-width: 1px;
border-color: #CCC;
border-style: solid;
border-left-width: 4px;
border-left-color: #000066;

font-family: Courier, monospace;
line-height: 115%;
clip : auto;
overflow : auto;

padding: 1em;
padding-left: 1.5em;
margin: 1em;
margin-left: 2em;

/* white-space:nowrap; if you want DIV instead of PRE */

This class should be used in a <PRE> or in a <DIV> element, depending on your needs. If you don't have to format something else inside the same block with HTML code, just use a <PRE> tag; but remember that every space or tab inside the text will be "as is" in the output (the HTML page). License: just cite this blog in the comments or somewhere else, and you can use and abuse of it =)

Little note: due to Blogspot's buggy post editor, I had to add a non-breakable space ( ) at the beginning of the margin-right row. Unfortunately, every space in the end of a line in the code editor, even if the line is broken for word-wrap, is considered useless and is trimmed out... Without this addiction, the margin-right row is not aligned with the other rows.
Moreover, every time you write the " " string in the HTML editor, and you edit the post again with the wysiwyg editor, it magically disappears and you have to edit the HTML code again... Buggy, buggy Blogspot!

The icing on the cake: If your code is very long (e.g. over 50 lines) but you don't want a such high box in your blog, just add the CSS max-height property, preferably to a value expressed in em (e.g. to about 30em) and a vertical scroll bar will appear if needed.

No comments:

Post a Comment