i am dustin diaz

a JavaScriptr...

boosh.

don't worry about it.

Styling Code Boxes

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.

this is who i am

Hi, my name is Dustin Diaz and I'm an Engineer @ObviousCorp. Previously @Twitter, @Google, and @Yahoo, author of Strobist® Info co-author of JavaScript Design Patterns, co-creator of the Ender JavaScript Framework, a Photographer, and an amateur Mixologist. This is my website. Welcome!

On this site I write about JavaScript. You can also follow along with my open-source work on Github.

This site is optimized and works best in Microsoft Internet Explorer 6.