Monday 30 April 2012

Wrapping pre tag text using css


What Is Pre-Formatted Text?

Pre-formatted text is added to your web pages using the PRE tag.

It is used to be very common to see web pages with blocks of pre-formatted text. Using the PRE tag to define sections of the page as formatted by the typing itself was a quick and easy way to get the text to display as you expected it to. This is because pre-formatted text is defined as text in which the structure is defined by typographic conventions rather than by the HTML.

Try the PRE tag on your website with various different spacings and carriage returns. For example, try pasting the following into your web page HTML (leave the spaces exactly as they are written):


<pre>
    Read each statement
      carefully
         and
      understand
   the meanings....
    Then share them with someone special.
</pre>

Basically HTML collapses the white space in the document. This means that carriage returns, spaces, and tab characters are all collapsed to one space. If you typed the above quote into a typical HTML tag like the P tag, you would end up with one line of text:


    Read each statement carefully and understand the meanings....Then share them with someone special.


The PRE tag leaves the whitespace characters alone. So line breaks, spaces, and tabs are all maintained in the browser. Putting the quote inside a PRE tag results in:


    Read each statement
      carefully
         and
      understand
   the meanings....
    Then share them with someone special.


But the PRE tag does more than just maintain the spaces. In most browseres, it is written in a monospace font. This makes the characters in the text all equal in width. In other words, the letter i takes up as much space as the letter w. But you can change this with style sheets.

Wrapping pre tag text in a div using css


When using pre tags in html to display code blocks it will ignore the div boundaries and not wrap the text by default. By adding some css for pre tags this can be accomplished as follows.

Hint: Another option is to use overflow:auto which will add scroll bars for the content.


pre, code{
 /*Wrap pre tag text for all popular browsers*/
 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 */
 word-wrap: break-word;  /* Internet Explorer 5.5+ */
 /*Or use overflow:auto ----------- */
 /*overflow:auto;*/
}

This will allow your long code to wrap properly and look like this.


Eg:-
ABCDEFGHIJKLMNOPQRSTUVWXYZ;ABCDEFGHIJKLMNOPQRSTUVWXYZ;ABCDEFGHIJKLMNOPQRSTUVWXYZ;ABCDEFGHIJKLMNOPQRSTUVWXYZ;ABCDEFGHIJKLMNOPQRSTUVWXYZ;

2 comments:

  1. where can i found CSS for pre tag to edit it ?

    application.css ?

    ReplyDelete
  2. Just write your own styling for pre tag.

    ReplyDelete