
In this post, I share some basic CSS to help style your pre tags for both screen and print media.
The HTML
It’s fine to use<pre>
tags on their own, but if you include <code>
tags like so:<pre><code>..that gives you a bit more flexibility in terms of styling with CSS. Let’s take a look.
[ include pre content here ]
</code></pre>
CSS for screen display
One thing that’s great style-wise about <pre> tags is that they preserve the white space (spaces and line breaks) for any content that is included, so it’s perfect for displaying code snippets. With that in mind, here are some basic styles to make <pre> tags look great when displayed via web page:/* pre */
pre {
box-sizing: border-box;
width: 100%;
padding: 0;
margin: 0;
overflow: auto;
overflow-y: hidden;
font-size: 12px;
line-height: 20px;
background: #616161;
border: 1px solid #777;
/*background: url(lines.png) repeat 0 0;*/
padding: 10px;
color: #fff;
}
pre code {
padding: 10px;
color: #fff;
}
CSS for print display
So at this point your <pre> tags are styled for screen display (web pages), but how to make them look good on the printed page? Here is some CSS that you can include that will make your <pre> content look clean and readable when someone prints out one of your web pages.@media print {
pre {
overflow-x: auto;
white-space: pre-wrap;
white-space: -moz-pre-wrap !important;
white-space: -pre-wrap;
white-space: -o-pre-wrap;
word-wrap: break-word;
background: #fff;
}
}
Make “Pre” Text Wrap
Text in <pre> tags doesn't wrap by default. For example, see the code snippet below! If this is causing layout problems, one solution is to give the pre block an overflow property to hide the excess or cause it to scroll. The other solution is to have it wrap./* Browser specific (not valid) styles to make preformatted text wrap */
pre {
white-space: pre-wrap;
/* css-3 */
white-space: -moz-pre-wrap;
/* Mozilla, since 1999 */
white-space: -pre-wrap;
/* Opera 4-6 */
white-space: -o-pre-wrap;
/* Opera 7 */
word-wrap: break-word;
/* Internet Explorer 5.5+ */
}
i always think that css is the best method for web development :)
ReplyDelete