Html pre tag can be used to display code on WordPress blog or any site. HTML pre tag represent preformatted text. Text within this element is typically displayed in a non-proportional font exactly as it is laid out in the file. This article will cover few simple css styles which you can use along with pre to display code.
Defined width and no word wrap
Here is css style code which can be used to in case you donot want any wrapping of words for long lines.
<style type="text/css"> pre { width: 40%; max-height: 400px; color: #444; padding: 10px; background: #eee; border: 1px solid #ccc; border-radius: 5px; word-wrap: normal; overflow: auto; } </style> <pre> #!/usr/bin/python ## print hello world multiple times print "Hello World! Hello World! Hello World! Hello World!"; </pre>
Few points to note:
- border-radius (HTML5 feature) does not work in IE8 but does not cause any issue also.
- We have used width in percentage. You can also use fixed width.
- text wraps only at line breaks.
Defined width and wrap words for long lines
Here is css style code which can be used to in case you want wrapping of words for long lines.
<style type="text/css"> pre { width: 40%; max-height: 400px; color: #444; padding: 10px; background: #eee; border: 1px solid #ccc; border-radius: 5px; word-wrap: normal; white-space: pre-wrap; overflow: auto; } </style> <pre> #!/usr/bin/python ## print hello world multiple times print "Hello World! Hello World! Hello World! Hello World!"; </pre>
Note that css white-space: pre-wrap
causes longs lines to be wrapped whenever needed along with line breaks.
Additional notes
- Note that pre can also be mimicked by using div with the following style:
div { font-family: courier, monospace; white-space: pre; }
- There are couple of javascript based code prettify libraries like Google code prettify which are worth looking at. These will have some overhead of extra js and css though.