Open In App

How to Wrap Text in HTML?

Last Updated : 25 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

To wrap text in HTML, you can use the default behaviour of block-level elements like <p>, <div>, and <h1>, which automatically wrap text to fit within their parent container. For more control over text wrapping, you can use CSS properties like word-wrap, white-space, and overflow-wrap to determine how the text behaves inside an element.

Using Block-Level Elements

The simplest way to wrap text in HTML is to place the text inside a block-level element, such as <p>, <div>, or <h1>. These elements automatically handle text wrapping based on the width of their parent container.

HTML
<div>
    <p>This paragraph will automatically wrap text to the next line
        if it doesn't fit within the width of the container.</p>
</div>

Output: The <p> element automatically wraps the text inside it when the content exceeds the width of the container.

wrap-text-block-level
Wrap Text in HTML

Alternative Approaches to Wrap Text

Using the <pre> Tag

By using this approach you can control text wrapping in HTML using CSS. By setting white-space: nowrap, the text remains on a single line without wrapping. In contrast, using word-wrap: break-word allows the text to wrap within the container when it exceeds the width.

Syntax

white-space: nowrap; - Prevents text from wrapping.
word-wrap: break-word; - Allows text to wrap, breaking long words if needed.

Example: Example of wrapping text in HTML, with two boxes: one without text wrapping and one with text wrapping.

HTML
<h3>GeeksforGeeks</h3>
<div class="box nowrap">
    <p>
        This is a long line of
        text that will not wrap inside the box.
    </p>
</div>
<div class="box wrap">
    <p>
        This is a long line of text
        that will wrap inside the box.
    </p>
</div>
CSS
/*style.css*/

.box {
    border: 2px solid black;
    width: 200px;
    height: 100px;
    margin: 10px;
    padding: 10px;
}

.nowrap {
    /* Prevent text from wrapping */
    white-space: nowrap;
    /* Hide overflow */
    overflow: hidden;
}

.wrap {
    word-wrap: break-word;
    /* Enable text wrapping */
}

Output

word-wrap-pre-tag
How to Wrap Text in HTML

Using the white-space CSS Property

The white-space property controls how white spaces inside an element are handled, and it can be used to enable text wrapping.

Syntax

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

Example: Enabling text wrapping using the white-space property.

HTML
<style>
    .text-wrap {
        white-space: normal;
        width: 250px;
        border: 1px solid black;
    }
</style>

<body>
    <h3>GeeksforGeeks</h3>
    <p class="text-wrap">
        This paragraph will automatically
        wrap the text within the specified width.
        The white-space property allows text
        wrapping.
    </p>
</body>

Output

word-wrap-white-space
How to Wrap Text in HTML

Next Article
Article Tags :

Similar Reads