Thứ Ba, 22 tháng 3, 2011

Styling Code Snippets with CSS

Styling Code Snippets with CSS

Tags:
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 {
 /*--Code Goes Here--*/
 /*--Code Goes Here--*/
 /*--Code Goes Here--*/
 /*--Code Goes Here--*/
}
</code></pre>

CSS

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;
}

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.
print.css
pre {
 overflow-x: auto; /* Use horizontal scroller if needed; for Firefox 2, not needed in Firefox 3 */
 white-space: pre-wrap; /* css-3 */
 white-space: -moz-pre-wrap !important; /* Mozilla, since 1999 */
 white-space: -pre-wrap; /* Opera 4-6 */
 white-space: -o-pre-wrap; /* Opera 7 */ /*
 width: 99%; */
 word-wrap: break-word; /* Internet Explorer 5.5+ */
}

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!

Related Resources

Related Posts

Không có nhận xét nào:

Đăng nhận xét