How To Display Code Examples On Your Website Tutorial
What is the "best" way to show code examples one your site? Well, after doing a lot of research and even more trial and error, I came to the conclusion that using the <pre> tag was the best way to show my code examples. Mainly, because it gave me the ability to give my <pre> a max-height. However, before you place your code on your site, you will need to use a code converter to change all these < > to these < >. This prevents the browser from trying to render your code. Then just copy and paste it into your <pre> and your done!
pre { display:block; border:#000 solid 1px; overflow:auto; max-height:340px; font-size:12px; width:535px; padding:10px; background:#E0E0E0; margin:2em 0; }
If you want your code to wrap, then use the rules below as well. However, you will find, as I did, that a few of these do not validate. Although I recently read that the W3C is planning on including word-wrap: break-word; in CSS-3. So soon we can have our cake and eat it too.
pre {
white-space:pre-wrap;/* css-3 problematic browser support */
}
If you want IE6 to have a max-height as well, then you'll need to feed it an IE expression to simulate max-height.
pre {
height: 340px; /* defaults to this height if JS is turned off */
height: expression( this.scrollHeight > 339 ? "340px" : "auto" );
}
IE expressions don't validate though, so place the above IE specific code in a seperate ie6.css and link to it by placing this in the <head>.
<!--[if IE 6]> <link href="ie6.css" rel="stylesheet" type="text/css" media="screen"> <![endif]-->