Search code examples
htmlcsspre

How to use Pre tag to restrict word break in HTML


I'm using a <pre> tag in my design. The thing is my pre even breaks the words at the end of the line. Say I'm at the end of the line and if there is a large word then it breaks it. For example at the end of the line we have a large word say STACKOVERFLOW.
So my pre tag display the word STACKOVERFLOW as:

STAC
KOVERFLOW

Where as it should show the whole word in the new line.
Following is my code for pre tag:

pre{
        white-space: pre-wrap;
        word-wrap: break-word; 
    }

Following is my HTML Code:

<div uib-carousel active="active" class="text-primary">
  <div uib-slide index="$index" class="uibSlider" ng-repeat='summary in desc'>
<pre class="text-justify">{{summary.info}}</pre>
</div>
</div>

Solution

  • See the w3 specification for the word-wrap property:

    ‘break-word’
    An unbreakable "word" may be broken at an arbitrary point if there are no otherwise-acceptable break points in the line. Shaping characters are still shaped as if the word were not broken, and grapheme clusters must together stay as one unit. No hyphenation character is inserted at the break point.

    Because you're using the 'break-word' rule, this means that your long words will be broken if there is no width left in the container and if there are no other more acceptable break points.

    Instead try using the 'normal' rule:

    ‘normal’
    Lines may break only at allowed break points. However, the restrictions introduced by ‘word-break: keep-all’ may be relaxed to match ‘word-break: normal’ if there are no otherwise-acceptable break points in the line.