CSS Word Break and White Space

1. Word Break

  • Purpose: The word-break property controls how long words are broken when a line of text reaches the end of its container.
  • Syntax: element {
         word-break: normal; /* Default */
         /* or */
        word-break: break-all;
         /* or */
        word-break: keep-all;
        /* or */
        word-break: break-word;
    }
  • Values: 
    • normal: Words are only broken at allowable break points (like spaces or hyphens).
    • break-all: Words can be broken at any character.
    • keep-all: Words are never broken, even if they overflow the container.
    • break-word: Words can be broken at any character, but only as a last resort to prevent overflow.
  • Example:
p {
width: 200px;
word-break: break-word;
}

This will allow words to be broken within the paragraph if they are too long to fit within the 200px width.

2. White Space

  • Purpose: The white-space property controls how an element handles and displays white-space (spaces, tabs, newlines).
  • Syntax: element { white-space: value; }
  • Values: 
    • normal: (Default) Collapses multiple spaces into a single space and allows line breaks where necessary.
    • nowrap: Prevents line breaks within an element, even if the text overflows the container.
    • pre: Preserves all whitespace (spaces, tabs, newlines).
    • pre-wrap: Preserves whitespace, but allows line breaks where necessary to prevent text overflow.
    • pre-line: Preserves whitespace, but collapses multiple spaces into a single space.
  • Example:
<p>This is a paragraph 
with some extra spaces.</p>
//This is HTML Code
p {
white-space: pre;
}
//This is CSS Code
  • The p tag contains extra spaces and a new line.
  • The white-space: pre; rule will preserve all the extra spaces and the newline, displaying the text exactly as it appears in the HTML.
Scroll to Top