How to use html pre tag to display code
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.
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.
pre with defined width and no word wrap
Here is css style code which can be used to in case you dont want any wrapping of words for long lines.
<style type="text/css"> pre { width: 80%; 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>
Here is how it looks when rendered:
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.
pre with defined width and word wrap in 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: 80%; 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>
Here is how it looks when rendered:
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.
تم النشر يوم
الأربعاء، 24 يوليو 2013 ' الساعة
ليست هناك تعليقات:
إرسال تعليق