How to word wrap in HTML


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.

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>
Output:
This is a Div. I am going to show how a looooooooooooooooooooooooooonggggggggggggggggggggggggg text without any breaks will look like.
Advertisements
Try Out Code2care Dev Tools:

Advertisements



Android Java Linux Microsoft Google Python macOS Notepad++ Microsoft Teams CSS PHP SharePoint Html Linux C Programs Bootstrap jQuery Sublime Android Studio Facebook Eclipse WhatsApp News MySQL Json HowTos JavaScript FTP S3


Advertisements


Code2care is an initiative to publish and share varied knowledge in programming and technical areas gathered during day-to-day learnings and development activities.

Students and Software Developers can leverage this portal to find solutions to their various queries without re-inventing the wheel by referring to our easy to understand posts. Technical posts might include Learnings, Tutorials, Trouble-Shooting steps, Video Tutorials, Code Snippets, How Tos, Blogs, Articles, etc.
🎉 We are celebrating the 10th years of Code2care! Thank you for all your support! We hope we made a difference.
We strong support Gender Equality & Diversity.

We stand in solidarity with Ukraine - Make a donation to UNHCR - https://donate.unhcr.org/in/en-in/ukraine-emergency