How to word wrap in HTML


Posted on : Wed, 20th May 15 10:41 am UTC
2314 votes

If you are using a long word without any break in between then the text might extend beyond the allocated area and push out giving a bad experience to end users.
Use the word-wrap property and set it to break-word, additionally a fixed width needs to be specified.

For example, below is some sample text in a Div with a long word without a break. Notice, how it goes outside the allocated area (width = 300px).

This is a Div. I am going to show how a looooooooooooooooooooooooooonggggggggggggggggggggggggg text without any breaks will look like.


Now let us look at the same example, but using the word-wrap property (word-wrap:break-word). Notice how neatly the text is wrapped and aligned.

This is a Div. I am going to show how a looooooooooooooooooooooooooonggggggggggggggggggggggggg text without any breaks will look like.


Here is the code (a fixed width is important here) -

<div style="background:lightgray;width:300px;word-wrap:break-word">
This is a Div. I am going to show how a looooooooooooooooooooooooooonggggggggggggggggggggggggg text without any breaks will look like.
</div>

Code2care's mission is to share varied knowledge in technical and non-technical areas gathered during day-to-day learnings and development activities so that our visitors can leverage this portal to find solutions to their queries without re-inventing the wheel. Technical posts include Learnings, Tutorials, Video Tutorials, Code Snippets, Tips-n-tricks.

Follow us : Facebook - Twitter - Google +