WordPress – Add and Properly Display Code

Background
While attempting to paste java code from an Android application into a WordPress blog, I discovered WordPress ignores all the white spaces and allows the text to run over the margins. Adding the <pre></pre> html tags respects the white spaces but does not respect the margins.

Solution
In the end, I added a few lines of code to the theme’s style.css file that force the <pre></pre> to respect whitespace and the theme margins. Below is an example of the adjusted pre tags and also contains the actual modifications to the style.css file.

Sources
Blog by Greg Rickaby – Adjust WordPress to support proper code display
http://codex.wordpress.org/Writing_Code_in_Your_Posts

/* Code
------------------------------------------------------------ */

pre {
	background-color: #dbdbdb;
	font-family: "Consolas", "Bitstream Vera Sans Mono", "Courier New", Courier, monospace !important;
	font-size: 13px !important;
	font-weight: normal !important;
	font-style: normal !important;
	text-align: left !important;
	line-height: 20px !important;
	border-left: 3px solid #75DB75;
	padding: 10px;
	margin: 0 0 15px 0;
	overflow: auto;
}

pre::selection {
	background-color: #3399ff;
}

code {
	background-color: #FFFF9E;
}

Leave a Reply

Your email address will not be published. Required fields are marked *

*