JSW189
JSW189

Reputation: 6325

Why do textareas break long words (and why don't divs break long words) when it exceeds the width?

Let's say I have two boxes: div.box and textarea.box, each of which has the same fixed width and height. Each also has identical text including one verrryyyyy long word, followed by a series of short words.

The setup might look like this:

CSS:

.box {
    width: 400px;
    height: 100px;
}

HTML:

<div class="box">
looooooooooooooooooooooooooooooooooooooooooooooooooooooooong_word and short text
</div>

<br><br>

<textarea class="box">
looooooooooooooooooooooooooooooooooooooooooooooooooooooooong_word and short text
</textarea>


Using the above code, the div does not break the long word, then begins on the next line with the series of short words:

div.box image

However, the textarea breaks the long word:

textarea.box image

My question: Why does this happen? What default CSS is causing the div to keep the long word on one line (i.e. not break the word), but the textarea to break it?

JS Fiddle Example.

Upvotes: 6

Views: 10051

Answers (3)

Boaz
Boaz

Reputation: 20230

The difference is in the default value of the word-wrap property of each element.

By default the browser's native stylesheet applies word-wrap:normal to the div element, whereas to the textarea element it applies word-wrap:break-word.

In other words, for div elements the browser assumes that if the text overflows the specified dimensions, whole words cannot be broken to fit the container, while for textarea elements it assumes that word breaking is acceptable. This difference becomes very apparent when (as in this case) the overflow is not suppressed.

Upvotes: 4

James Coyle
James Coyle

Reputation: 10428

Chrome default textarea styling:

textarea {
    -webkit-appearance: textarea;
    background-color: white;
    border: 1px solid;
    border-image: initial;
    -webkit-rtl-ordering: logical;
    -webkit-user-select: text;
    -webkit-box-orient: vertical;
    resize: auto;
    cursor: auto;
    padding: 2px;
    white-space: pre-wrap;
    word-wrap: break-word;
}

The word-wrap: break-word; is the cause.

The overflow property can only hide the overflowing content or allow it to be scrolled. Use word-wrap: break-word; to allow long words to be broken.

Upvotes: 7

Because that's not what overflow does, you may be want to take a look at the word-wrap property (http://www.w3.org/TR/css3-text/#overflow-wrap).

You want to apply word-wrap: break-word; to the element.

Upvotes: 1

Related Questions