CSS `word-break`: Managing Word Wrapping and Overflow in Web Design

Learn how to control word breaking and handle text overflow in your CSS layouts using the `word-break` property. This tutorial explains different `word-break` values (normal, break-all, keep-all, break-word), demonstrating their effects on text rendering and providing techniques for creating clean and user-friendly text layouts.



Controlling Word Breaking with CSS `word-break`

Understanding `word-break`

The CSS `word-break` property controls how words are broken (wrapped) at the end of a line. This is particularly important when dealing with long words or text that might overflow its container. By using this property, you can define how the browser handles lines that don't fit within the container's width.

`word-break` Property Syntax and Values

The syntax is:

word-break: normal | keep-all | break-all | break-word | initial | inherit;

Here's what each value means:

  • normal (default): Words are only broken at natural break points (like spaces or hyphens).
  • keep-all: Words are not broken; they may overflow their container. Avoid using this for CJK (Chinese/Japanese/Korean) text.
  • break-all: Words are broken at any character to prevent overflow. Hyphens are not used.
  • break-word: Long words are broken to prevent overflow.
  • initial: Resets the property to its default value (normal).
  • inherit: Inherits the value from its parent element.

Examples of `word-break`

These examples demonstrate the different `word-break` values. You'd need to include corresponding HTML elements (e.g., paragraphs with long words) and apply these CSS rules to see the effects in a browser. The container element would need to have a defined width for `break-all` and `break-word` to be effective.

Example 1: `word-break: normal;`

Shows how text breaks only at spaces and hyphens.

Example 2: `word-break: keep-all;`

Illustrates that words are not broken, even if they overflow.

Example 3: `word-break: break-all;`

Shows how words are broken at any character to prevent overflow.

Example 4: `word-break: break-word;`

Demonstrates how long words are broken to fit within the container.

Example 5: Comparing All Values

This example shows a comparison of all four values side-by-side within a contained area.

Conclusion

The `word-break` property gives you control over how text wraps and handles overflow. Choosing the right value depends on your specific layout needs and the type of text you're working with (e.g., using `keep-all` for CJK text is not recommended). Understanding how these different values behave helps you create well-structured and readable web pages.