with Imagination: by Dustin Diaz

./with Imagination

A JavaScript, CSS, XHTML web log focusing on usability and accessibility by Dustin Diaz

Styling Code Boxes

Sunday, February 26th, 2006

Something every developer with a blog runs into is how to style their code when outputting it for all the web to see, copy, and paste. So without mucking around with a savvy intro to the rest of this tutorial…

The XHTML

With semantics in mind, I generally like to give each code box a heading describing in brief what the code is doing. For example, see below:

Demo of a header

/* Hello World */
/* I'm a comment in my code! */

In order to do that, I use a level three header (<h3>) directly above the code. Then for the code itself I typically use the combination of a <pre> element directly followed by a <code> element. In addition to just having a level three header, I also use a class of code on the <h3> element to distinguish it from the other level three headers I may have within the flow of an article posting. So the entire XHTML looks like this:

Sample HTML code for code blocks

<h3 class='code'>Sample HTML code for code blocks</h3>
<pre><code>
// My code will go here
</code></pre>

Cool, now that we have that finished. Just add your CSS spice, and we be outy:

CSS for styling code blocks

#article h3.code, #article pre {
	cursor:pointer;
}
#article h3.code {
	color:#000;
	font:bold 1em 'courier new',courier,monospace;
	text-align:right;
	margin:1em 0 0 0;
	padding:3px;
	border:1px dotted #fff;
	border-bottom-width:0;
	background:#50ff4c;
}
#article pre {
	font:1em/1.2em 'courier new',courier,monospace;
	color:#50ff4c;
	background:#333;
	border:1px dotted #fff;
	padding:1em;
	margin:0 0 1em 0;
	overflow:auto;
}

And voila! You’ve styled your code boxes. Have a good night, I’m here all week till thursday. Try the Monterey Chicken with a shot of Jack. It’s great. Peace.

22 Responses to “Styling Code Boxes”

  1. Mike Rumble

    Nice to see nice wide code boxes on this site.

    One of my pet hates is when code boxes are too narrow to show the long lines of code they house, prompting the dreaded horizontal scroll bar to rear it’s ugly head.

    Seems to happen with most of the out-of-the-box blog templates.

  2. Glen C.

    One thing I would mention is how to handle the inevitable overflow from long lines of code. I always use overflow:auto; but I’m sure another option exists.

  3. Andy Beeching

    I like using this script to format code examples

    http://www.danwebb.net/workspace/CodeHighlighter/

    as used on the vivabit blog:

    http://www.vivabit.com/bollocks

  4. Nick Presta

    Yes, the large code boxes are refreshing. The bright and contrasting colors are also helpful for indentifying code without resulting to widths and margins.

  5. Dustin Diaz

    Yes, these code boxes are indeed nice and wide, but I too, as you might have noticed, have the overflow:auto for those cases when it’s too wide (long).

    @Andy, The purpose of this example was how to do this with CSS only. The JavaScript solutions are obviously going to be a lot cooler - and anytime you’re doing code-hilighting, well, that’s always fun. I think the most impressive one is what they have on the Sitepoint Blogs

  6. Scott

    I was just playing with code boxes for my site, because I wrote a tutorial on using the moo.ajax class from Mad 4 Milk. I didn’t add headings to the code boxes, but it’s a great idea. Perhaps when i get a moment, I’ll do so.

    When styling my boxes, I grabbed some ideas from Quirks Mode. I threw in the overflow-x and overflow-y properties for browsers that support them, and to avoid vertical scrolling within code blocks (I prefer to just display the whole thing.)

  7. paul haine

    What’s the purpose of using cursor: pointer; on the code blocks? It just makes me think I should be able to click the blocks and cause something to happen.

  8. Andy Beeching

    I agree Dustin, a pure CSS solution would be perfect, I simply put the link to the script up there to be used in conjunction with your styling so as to get the best of both worlds. Plus, given the audience (for most web-orientated blog sites), the javascript-enhanced version will most likely be shown.

  9. Ollie

    I’m curious about your use of

    cursor:pointer;

    Personally I associate the pointer cursor with something that responds to a click. What is it communicating here?

    Perhaps there is some JavaScript (Copy would be nice) that doesn’t work in my browser?

  10. Klaus Hartl

    Hi Dustin,

    why do you use cursor: pointer for the whole pre element?

  11. Klaus Hartl

    I wanted to mention another thing: I experienced overflow: auto; not working in IE/Win without specifying any width. Therefore one should add width: 90% - not 100% here, because there is a padding for the pre element.

    If you want to use 100% move the padding to the code element: code { display: block; padding: 1em; }.

  12. Jason Beaird

    Looks good Dustin. Just out of curiosity though, why set the cursor to pointer? That, to me at least, indicates link. I think the default text cursor works best here, especially if people are going to be copying/pasting from your code.

  13. P.J. Onori

    Very nice. I’m definitely going to rethink my code boxes after reading this. I’ve never used the ‘pre’ tag but after reading about it, but I see how they certainly work well together.

    Great article.

  14. Dustin Diaz

    @All: I was only using the pointer because it was a style preference I liked. I was a bit surprised so many folks pointed out that one thing rather than seeing the merit of everything else.

    Afterall, you know what to do, just remove that style rule and voila. Everyone’s happy. Heh. You’d think a group from digg just stopped by (inside joke) ;)

  15. Cheyne

    Very good article, keep up the good work. I agree with Jason’s comment on the link cursor. It’s not so good for usability.

    And for the record I arrived from del.icio.us, not digg ;)

    http://www.thewebdesignblog.com

  16. Natalie

    While we’re on the subject… I’m with Paul and Ollie. I keep trying to click your code thinking there’s some secret link I’m missing. I don’t “digg” the pointer. :D

    Actually, I do love the headers atop the code. I have trouble styling code because sometimes I want inline code when it’s just a quick "<div id="blahblah"></div>" thought.

  17. Dustin Diaz

    Well, just for reference, I used to have a reason for having the heading entail a pointer cursor. That was when I had them be collapsable via collapsable effects with Scriptaculous. In the redesign I decided against scriptaculous due to its bulkiness. I figured I would eventually find an alternate solution to get the same effect.

  18. Jason Beaird

    I have this bad habbit of opening all the stories I want to read out of bloglines in new tabs, and then reading them all individually as I get a chance during the day without refreshing. It makes me feel better that bloglines says I have no unread news…even though I really haven’t read them yet. To make matters worse I happened to open this post the day before when there were only 2 or 3 comments. So…sorry for adding to the digg-like ignorance with my cursor question. :)

  19. Ollie

    Thanks Dustin, I think your suggestion of headings for each code block is an excellent one, thank-you!

    I was introduced to the <pre><code> combo by Markdown .

    Note: Before leaving this comment I was careful to refresh the page to ensure it was not already redundant :)

  20. Jason

    The code boxes stand out nicely on the site — but I’ve yet to find a web browser that prints them without lopping off the right side of any long lines. Any chance of correcting this (likely) oversignt? The printing issue makes it hard to actually use the code that’s in them in printed form (like me reading them on the subway home at night!).

  21. Klaus Hartl

    @Jason: The printing of the pre can be controlled for the print: to avoid lopping off, there should be something defined like pre { white-space: normal; } in a style sheet designated for print.
    So this has nothing to do with the browser (which only renders the default style for the pre element).

  22. Chad’s dailies » Blog Archive » links for 2007-03-25

    [...] Styling Code Boxes (tags: CSS articles) [...]

Get "JavaScript Design Patterns"

"As a web developer, you'll already know that JavaScript™ is a powerful language, allowing you to add an impressive array of dynamic functionality to otherwise static web sites. But there is more power waiting to be unlocked--JavaScript is capable of full object-oriented capabilities, and by applying OOP principles, best practices, and design patterns to your code, you can make it more powerful, more efficient, and easier to work with alone or as part of a team."

Buy JS Design Patterns from Amazon.com Buy JS Design Patterns from Apress

Submit a Prototype

All content copyright © 2003 - 2007 under the Creative Commons License. Wanna know something? Just ask.

About | Archives | Blog Search

[x] close

Loading...

Submit a prototype

By checking this prototype I agree that I am not submitting false credentials, pornography, or a hate crime website. I also understand that by submitting my entry I may or may not be accepted, and if accepted, my entry may be taken down at any given time if I violate these terms.