Styling code blocks
In this article I'll explain how to use CSS for styling code blocks.
Code blocks are generally formatted by using the pre element. Roger Johansson has proposed another
way to accomplish this task and I'll follow his example with further improvements.
Table of contents
The markup
The proposed markup for code blocks is the following:
Listing 1. Proposed markup for code blocks
<ol class="code"><li><code>/* static */</code></li>...omission...<li class="indent1"><code>gLexTableSetup = PR_TRUE;</code></li>...omission...<li class="indent2"><code>lt[i] |= IS_IDENT | START_IDENT;</code></li>...omission...<li class="indent3"><code>lt[i] |= IS_HEX_DIGIT;</code></li>...omission...<li id="last">...</li></ol>
Since we're dealing with computer code, the most semantic way to mark it up is by using the code element. Furthermore,
by using an unordered list instead of a pre element we can be sure that the content of the block will not overflow its
container when we change the size of the window or the dimensions of the container itself.
General styles
The general style are really simple.
Listing 2. General styles
ol.code {background: #e7e7f5;color: #333;margin: 0;padding: 0.5em;width: 55%;list-style: none;}ol.code li {border-bottom: 1px solid #666;}ol.code li#last {border-bottom: none;}ol.code code {font: small "Courier New", Courier, monospace;}
We've set a width, some padding, resetted the default margins and got rid of the list marker on the ol
element. All list items will have a bottom border, except the item with the ID #last. Finally, we've set
the font size and family on the code element.
Creating indentations
Also this step is actually simple.
Listing 3. Creating indentations
ol.code .indent1 {padding-left: 1em;}ol.code .indent2 {padding-left: 2em;}ol.code .indent3 {padding-left: 3em;}
We've created progressive, meaningful classes to be applied to the elements in the list. Each classes have a progressive left padding that actually creates the required indentations.
Adding a vertical scrollbar
Adding a vertical scrollbar to the code block requires only two simple declarations.
Listing 4. Adding a vertical scrollbar
ol.code {height: 100px;overflow: auto;}
The first declaration sets a height on the list. In order to make it work, the height must be always less than
the global amount of the list's content. By doing so, browsers are forced to let the content overflow its container.
The second declaration, in fact, deals with the overflowing content through the auto value of the
overflow property. Since the specifications state that in case of overflowing content browsers must always
provide a mechanism for viewing the content, browsers add a vertical scrollbar to our list.