How to Wrap the div Text in CSS – The Easy Guide

In web development, it’s common to display blocks of text within a <div> element. But sometimes, long words or unbroken content (like URLs) may overflow outside the container, breaking your layout.

To avoid this issue, CSS offers simple yet powerful properties to wrap text inside a <div> properly.

In this blog post, you’ll learn how to wrap text inside a div using CSS — with practical code examples and tips for responsive design.


🧱 What Is Text Wrapping?

Text wrapping means breaking and continuing text onto the next line when it reaches the edge of a container — such as a <div>, <section>, or other block-level elements.

By default, text in a <div> wraps automatically. However, certain scenarios (like long words or fixed-width elements) may require explicit handling using CSS.


✅ Basic Example: Automatic Wrapping

Here’s the default behavior — text wraps when it reaches the container’s edge:

🧾 HTML:

<div class="wrapper">
  This is some sample text that will wrap inside the div.
</div>

🎨 CSS:

.wrapper {
  width: 300px;
  border: 1px solid #ccc;
  padding: 10px;
}

✅ This will wrap normally — no special CSS is required.


❗ Problem: Long Words or URLs Don’t Wrap

Long strings like:

<div class="no-wrap">
  ThisIsAnExtremelyLongWordThatDoesNotWrapProperlyAndBreaksTheLayout
</div>

…can overflow the container.


💡 Solution: Use word-wrap or overflow-wrap

To force long words to wrap within the container:

✅ CSS Fix:

.no-wrap {
  width: 300px;
  border: 1px solid #ccc;
  word-wrap: break-word;       /* older syntax */
  overflow-wrap: break-word;   /* modern syntax */
}

This tells the browser to break long words if needed.


🧠 Additional Wrapping Options

1. white-space Property

Controls whether text wraps or not.

  • normal – default, wraps automatically
  • nowrap – prevents wrapping
  • pre-wrap – wraps, but preserves whitespace

Example:

.wrapper {
  white-space: normal; /* ensures automatic wrapping */
}

2. Handling Overflow Gracefully

.ellipsis {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

This will keep the text on one line and truncate with “…” if it’s too long.


🧾 Complete Example:

<!DOCTYPE html>
<html>
<head>
  <style>
    .text-box {
      width: 300px;
      border: 1px solid #000;
      padding: 10px;
      overflow-wrap: break-word;
    }
  </style>
</head>
<body>

  <div class="text-box">
    ThisIsAVeryLongWordThatWouldNormallyOverflowTheContainerButNowItWrapsCorrectly
  </div>

</body>
</html>

📌 Conclusion

To wrap text inside a <div>, you typically don’t need extra CSS. But for long words or fixed-width elements, you should use:

overflow-wrap: break-word;

or

word-wrap: break-word; /* for older browsers */

These ensure your layout stays clean and readable across devices.

Sharing Is Caring:

Leave a Comment