Cover Image for How to wrap text in CSS
132 views

How to wrap text in CSS

To wrap text in CSS, you can use the white-space property. The white-space property controls how white space (including line breaks) inside an element is handled.

By default, the white-space property is set to normal, which allows the text to wrap according to the available space in the element’s container.

Here’s an example of how to wrap text within an element:

HTML:

<div class="text-container">
  This is a long line of text that will wrap within its container.
</div>

CSS:

.text-container {
  white-space: normal;
}

In this example, we have a <div> element with the class “text-container” that contains a long line of text. By setting the white-space property to normal, the text will wrap to the next line when it reaches the edge of the container.

Other values of the white-space property include:

  • nowrap: The text will not wrap to the next line and will overflow the container if it exceeds the available space.
  • pre: The text will respect line breaks and spaces exactly as they appear in the source code, without wrapping or collapsing.
  • pre-wrap: The text will wrap to the next line when it reaches the edge of the container, and line breaks and spaces will be respected as they appear in the source code.
  • pre-line: The text will wrap to the next line when it reaches the edge of the container, and consecutive white spaces will collapse into a single space.

Here’s an example using the pre-wrap value:

HTML:

<div class="text-container">
  This is a long line of text that will wrap within its container.
</div>

CSS:

.text-container {
  white-space: pre-wrap;
}

In this case, the text will wrap to the next line when it reaches the edge of the container, while still respecting line breaks and spaces as they appear in the source code.

You can choose the appropriate white-space value based on your specific requirements for text wrapping.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS