Labs ICT
Pro Login

White Space

The white-space property controls how the browser handles whitespace characters (spaces, tabs, newlines) in text. It determines whether text wraps, collapses spaces, or preserves exact formatting. This property is more powerful than it sounds.

The Main Values

The most common values are normal, nowrap, pre, pre-wrap, and pre-line. Each handles whitespace differently.


/* Default: wraps, collapses spaces */
.normal {
  white-space: normal;
}

/* No wrapping, collapses spaces */
.nowrap {
  white-space: nowrap;
}

/* No wrapping, preserves all whitespace */
.pre {
  white-space: pre;
}

/* Wraps, preserves whitespace */
.pre-wrap {
  white-space: pre-wrap;
}

/* Wraps, preserves newlines only */
.pre-line {
  white-space: pre-line;
}
    

normal is the default — text wraps and multiple spaces collapse into one. nowrap prevents wrapping entirely, which is useful for single-line text.

Try it Yourself →

Preventing Text Overflow

white-space: nowrap combined with overflow: hidden and text-overflow: ellipsis is the classic single-line truncation pattern. This is essential for navigation menus, titles, and any place where long text must not break the layout.


.truncate {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 200px;
}
    

The text stays on one line, anything that overflows is hidden, and an ellipsis (...) appears at the end. This is one of the most commonly used CSS patterns.

Preserving Code Formatting

When displaying code snippets or poetry where whitespace matters, use pre or pre-wrap. These preserve all spaces and line breaks exactly as they appear in the HTML.


.code-block {
  white-space: pre;
  font-family: monospace;
}

.poem {
  white-space: pre-wrap;
  font-family: serif;
}
    

The difference: pre does not wrap (like the <pre> HTML tag), while pre-wrap preserves spaces but still wraps long lines. Use pre-wrap when you want formatting preserved but do not want horizontal scrolling.