الأربعاء، 24 يوليو 2013

How to use html pre tag to display code


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.

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:
pre-tag-long-lines-no-words-wrap Few points to note:
  1. border-radius (HTML5 feature) does not work in IE8 but does not cause any issue also.
  2. We have used width in percentage. You can also use fixed width.
  3. 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:
pre-tag-long-lines-words-wrapCss white-space: pre-wrap causes longs lines to be wrapped whenever needed along with line breaks.

Additional notes

  1. Note that pre can also be mimicked by using div with the following style:
    div {
      font-family: courier, monospace;
      white-space: pre;
    }
    
  2. 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 ' الساعة  1:57 م


ليست هناك تعليقات:

إرسال تعليق