Saturday, April 9, 2011

HowTo: CSS code boxes

The easiest way to create boxes for code in your website is to use CSS. This can be done by setting up your own custom element, or by defining the <pre> tag. I like to use the <pre> tag because it obeys spaces and line breaks. This is fine as long as you don't want to use the <pre> tag for anything other than code boxes. The CSS code I use to define the <pre> tag for this blog is as follows:

pre {

      border: solid 1px gray;

      font-size: 1.3 em;

      font-family: 'Courier New', Courier, monospace;

      color: #FFFFFF;

      margin: 10px;

      padding:10px;

      text-align: left;

      background-color: #000000;

      overflow-x: auto;

      white-space: pre-wrap;

      white-space: -moz-pre-wrap !important;

      word-wrap: break-word;

      white-space: normal;

}


If you run a Blogger.com blog, you can easily add this bit of CSS to your template. From your dashboard click the "Design" tab, then "Template Designer." Then click the "Advanced" tab, and scroll all the way down to "Add CSS." Copy/paste this code (or your own modified version of it) into the box and then click "Apply to Blog." Now, whenever you want to insert code into a blog post, simply wrap it with <pre> and </pre> tags.

If you are wondering about the white-space and word-wrap entries, they are to ensure that word wrap is on for all browsers. I got them from here.

No comments:

Post a Comment