Working with text overflow and wrapping in CSS

incss2 min read

Quick summary

Learn about various CSS properties that help you manipulate and style text effectively. This guide covers properties like `word-break`, `overflow-wrap`, `hyphens`, and more.

word-break

The word-break property specifies how words should break when reaching the end of a line. It can be used to prevent long words from overflowing their container.

/* Normal behavior */
word-break: normal;
 
/* If content exceeds the block's boundaries,
a line break can be inserted between any two characters */
word-break: break-all;
 
/* add line breaks whenever necessary,
without trying to preserve whole words */
word-break: break-word;
 
/* prevent line breaks from being applied to
Chinese/Japanese/Korean languages*/
word-break: keep-all;

overflow-wrap

The overflow-wrap(formerly known as word-wrap) property allows you to control how text should wrap when it overflows its container. This is particularly useful for preventing long words from breaking the layout.

/* Normal behavior */
overflow-wrap: normal;
 
/* Break words at any character */
overflow-wrap: anywhere;
 
/* Wraps long words onto a new line to prevent container overflow */
overflow-wrap: break-word;

The main difference with word-break: break-all:

  • word-break: break-all breaks words anywhere to prevent overflow
  • overflow-wrap: break-word wraps long words to a new line, keeping words together to prevent overflow.

See the example below:

hyphens

The CSS hyphens property controls how words break across lines. It can disable hyphenation, allow it only at specified points, or let the browser automatically insert hyphens where needed.

Hyphenation rules depend on the language. In HTML, the lang attribute defines the language. Browsers apply hyphenation only if this attribute is present and a matching dictionary is available.

hyphens: auto;
/* The browser can automatically break words at hyphenation points,
following any rules it chooses. */
 
/* Words break at line wraps only where break points
are explicitly specified within them. */
hyphens: manual;
 
/* Words will not break when wrapping to a new line,
even if break points are specified. Lines will only break at spaces. */
hyphens: none;

Hyphenation rules are not strictly defined in the specification, so the exact hyphen placement may vary between browsers.

Two Unicode characters are used to manually define possible line breaks in text:

U+2010 or ‐ – A "hard" hyphen that marks a visible break point. Even if the word isn't broken, the hyphen remains visible.

U+00AD or ­ – A "soft" hyphen, which is invisible and indicates where the browser should break the word if needed. In HTML, use ­ to insert a soft hyphen.

More info

Articles

YouTube