Definition & Usage
The white-space property is used to control how white space inside an element is handled.
Possible Values
- normal: Sequences of white space are collapsed. Line breaks are treated as spaces, and consecutive spaces are collapsed into a single space.
- nowrap: Sequences of white space are collapsed, and text will not wrap to the next line. It continues on the same line.
- pre: White space is preserved, and the text will only wrap on line breaks. Multiple spaces and line breaks are respected.
Using white-space with HTML Tables
In this example, the white-space: nowrap; is applied to the <td> and <th> elements, indicating that the text within the table cells should not wrap to the next line. The following CSS sets the white space handling:
In this example, the white-space: nowrap; ensures that the text within each cell does not wrap to the next line. Adjust the white-space value according to your specific design requirements.
Tips
Prevent Line Breaks with white-space: nowrap
If you want to prevent line breaks within table cells, use white-space: nowrap.
Preserve Whitespace with white-space: pre
If you want to preserve both spaces and line breaks, use white-space: pre.
Allow Line Breaks with white-space: pre-line
If you want to preserve line breaks but collapse other whitespace, use white-space: pre-line.
Useful for Code or Text Formatting
The white-space property is particularly useful when displaying code snippets or preformatted text inside table cells.
Combine with Other Properties
Combine white-space with other CSS properties like overflow and text-overflow to control the rendering of text.
Consider Responsive Design
When using white-space, consider how it affects the responsiveness of your table. For example, preventing line breaks (white-space: nowrap) might not be suitable for small screens.
Test with Various Content
Test the white-space property with different types of content to ensure it behaves as expected in various scenarios.
Avoid Unnecessary Whitespace in HTML
Minimize unnecessary whitespace in your HTML markup to have better control over the presentation using white-space.