Anyone who has ever tried to insert a line or block of code into their WordPress posts knows firsthand how frustrating it can be to get the code to display correctly – without funny characters, or lines running off the page, etc. Here is the method I use to get blocks of code to display correctly in a post.
Copy and paste this code into your stylesheet:
pre {
font-family: courier,"courier new",monospace;
font-size: 12px;
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+ */
}
Now, the next time you add a line of code to your posts, simply highlight the code, and select “Preformatted” rather than “Paragraph” in the drop down menu at the top of your post box.
Or – if you prefer to work with the HTML directly, add the tags <pre> and </pre> around the line or block of code that you are trying to style.
And of course, you can further customize the way codes display in your WordPress posts by adding background color, borders, etc. to the <pre> element in your stylesheet.
Let me know if you have problems or questions.
