CSS: better styling for 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.

The markup

The proposed markup for code blocks is the following:

<ol class="code">
<li><code>/* static */</code></li>
<li class="indent1"><code>gLexTableSetup = PR_TRUE;</code></li>
<li class="indent2"><code>lt[i] |= IS_IDENT | START_IDENT;</code></li>
<li class="indent3"><code>lt[i] |= IS_HEX_DIGIT;</code></li>
<li id="last">...</li>

View the example

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.

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;

View the example

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.

ol.code .indent1 {
padding-left: 1em;
ol.code .indent2 {
padding-left: 2em;
ol.code .indent3 {
padding-left: 3em;

View the example

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.

ol.code {
height: 100px;
overflow: auto;

View the example

The first declaration sets an 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 scrolling mechanism for viewing the content, browsers add a vertical scrollbar to our list.

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

One thought on “CSS: better styling for code blocks”

Leave a Reply

Note: Only a member of this blog may post a comment.