Using a Zebra Background Effect to Style Code Blocks with CSS
In this third part of a seven-part series on styling code blocks, I demonstrate how to add an engaging zebra background effect to a PHP fragment included in a web page. This background effect improves its readability. As you'll see, the process is very similar to assigning background images to other HTML elements, so you shouldn’t have major trouble implementing this effect in your own website.
Using a Zebra Background Effect to Style Code Blocks with CSS - Enhancing code snippet readability with a zebra background effect (Page 3 of 4 )
Certainly, one of the most common decorative effects that can be used with elements of a web page, such as tables, divs, lists and so forth, is a zebra background, which makes (at least in theory) the contents wrapped by these elements slightly more readable. In keeping with this concept, it’d be useful to apply this effect to online code snippets as well, right?
Fortunately, in this particular case building the effect in question is only a matter of assigning a tiny background image to the <pre> tag used in the previous web page. Since this image will have actually a width of only 1px and a height of 30px, below I included a magnified version of it, so you can see it more clearly how it looks. Here it is:
With the background image already set, creating a zebra background for the earlier code snippet is as simple as defining the following CSS styles:
/* <pre> selector */
pre {
width: 600px;
padding: 0;
margin: 0;
background: #fff url("bg_code_block.gif") left top;
overflow: auto;
overflow-Y: hidden;
font-size: 12px;
line-height: 15px;
border: 1px solid #808080;
}
/* <code> selector */
pre code {
display: block;
padding: 0;
margin: 0 0 0 20px;
}
Done. Now, each code block wrapped by the sequence of <pre><code> elements will be decorated with the zebra background image that you just saw. Quite possibly, the only detail worth noticing here is the extra “overflow-Y: hidden” rule, which is used for preventing Internet Explorer from displaying additional vertical scrollbars.
All right, now that the pertinent <pre> and <code> tags have been properly styled, the last thing that must be done is including the previous CSS styles in the web page containing my PHP snippet, so you can see how the zebra background is neatly displayed on the browser.
This last task will be performed in the following section. To get there, click on the link below and keep reading.