Formatting Code Snippets in a Blog Entry with CSS

Filed under Blogging, CSS

Since this blog is a relatively new thing for me, I’ve picked up quite a few tidbits while setting it all up.

One thing I just ran into is formatting code chunks. I’m guessing there’s loads of different ways to do it, but in my case, I just wanted something easy to tag, and with a nice format, but not necessarily “pretty printed” with color, keyword highlighting etc.

In researching it, I came across Nikhil Kothari’s blog. He has a number of nice things there, so check it out for everything else as well, but I noticed he was formatting code almost like what I had in mind.

The CSS he uses is:

pre {
 font: inherit;
 color: inherit;                        
 white-space: inherit;
 margin: 0;
}

The problem I had with this is that it tends to allow the text to flow over past it’s containing block on the right, which, to me, doesn’t look all that good.

Plus, to set off the code more, I’d prefer it indented to the left and right.

A little CSS reading later and I came up with this:

pre {
   font-family: 'Lucida Console', Courier;
   font-size: 10pt;
   color: inherit;
   white-space: no-wrap;
   margin: 0 3em 0 3em;
   overflow: hidden;
}

It gets the font right, the indents right, and just chops the text at the right edge. I suppose for some purposes, it might be better to wrap the code, but at least for what I need right now, it seems perfect.

Just Added: The above doesn’t quite work in all cases. Appearently, in IE6, overflow:hidden isn’t necessarily supported properly. You might also need to specify a Width property. In my case, I used:

pre {                        
   font-family: 'Lucida Console', Courier;
   font-size: 10pt;
   color: inherit;
   white-space: no-wrap;
   margin: 0 3em 0 3em;
width: 80%; overflow: hidden; }

Which seems to do the job just fine.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

*