How did we create and style consistent cross-browser Code Snippets with <pre> and <code> tags and some simple CSS.
The problem, not all browsers treat the padding of the <pre> tag the same. I know what your first thought was…”It’s Internet Explorer!”, wrong actually the culprit is Firefox
. In short Firefox doesn’t play well with spaces and tabs in the <pre> tag. Yes a CSS reset does go a long way in fixing this issue, but we wanted to further the control of our Code Snippets and do some fancy stuff to them as well.
Our solution…
We nest the <pre> and <code> tags allowing control of the margin, padding and backgrounds for each of the elements. Our HTML, CSS, PHP, javascript or whatever code goes inside the tags.
<pre><code>
<!-- Place Code Here -->
</code></pre>
The CSS for our <pre> and <code> tags. We control the padding in the <pre> tag and the spaces and tabs in the code are properly represented in the <code> tag.
pre {
padding: 0;
margin: 4px 0 12px 0;
border: 1px solid #ccc;
line-height: 20px;
background: url(/images/code-bg.gif) repeat-y top left #000;
width: 586px;
overflow: auto;
overflow-Y: hidden;
}
pre code {
margin: 0 8px 0 25px;
padding: 18px 0;
display: block;
color: #3C3;
}
So there you have it, simple yet effective in producing consistent results across all browsers.
Post your thoughts below…

Leave a Reply