Styling Code Snippets with CSS

Although there are many useful plug-ins out there that dress up code snippets, I would like to share a technique playing with the background of the <pre> and <code> tag with CSS.

Common Problem with FireFox

When trying to add some padding to the <pre> tag, FireFox creates a cross-browser bug where it interferes with the spaces created by the space or tab bar. See below for an example.
CSS FireFox Code Bug
Solution
We can go around this issue by nesting the <code> tag within the <pre> tag and specifying a margin in <code>.

HTML

Start out by placing your code snippet in between the <pre> and <code> tag. Note that anything inside of the <pre> tag is preserved (spaces and line breaks).
<pre><code>.classname {
    <span style="color: rgb(136, 136, 136);">/*--Code Goes Here--*/</span>
    <span style="color: rgb(136, 136, 136);">/*--Code Goes Here--*/</span>
    <span style="color: rgb(136, 136, 136);">/*--Code Goes Here--*/</span>
    <span style="color: rgb(136, 136, 136);">/*--Code Goes Here--*/</span>
}
</code>

CSS

<code>pre {
font-size: 12px;
padding: 0;
margin: 0;
background: #f0f0f0;
border-left: 1px solid #ccc;
border-bottom: 1px solid #ccc;
line-height: 20px; /*--Height of each line of code--*/
background: url(pre_code_bg.gif) repeat-y left top; /*--Background of lined paper--*/
width: 600px;
overflow: auto; /*--If the Code exceeds the width, a scrolling is available--*/
overflow-Y: hidden;  /*--Hides vertical scroll created by IE--*/
}
pre code {
margin: 0 0 0 40px;  /*--Left Margin--*/
padding: 18px 0;
display: block;
}
</code>

Make <pre> Tags Print Friendly

To make <pre> tags print friendly and make the code wrap to the next line, Tyler at www.longren.org shared a great technique to tackle this issue. If you are new to print style sheets, check out my previous tutorial.

Conclusion

If you haven’t dressed up your code snippets yet, now is a good time. Feel free to take the background images of my samples as well. If you have any questions or know of any other techniques, please share them!
taken from http://www.sohtanaka.com/web-design/styling-pre-tags-with-css-code-block/



Related Posts Plugin for WordPress, Blogger...