Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 244
JSW189 Avatar asked Dec 27 '22 09:12

JSW189


2 Answers

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.

like image 199
James Coyle Avatar answered Dec 28 '22 22:12

James Coyle


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.

like image 34
Boaz Avatar answered Dec 28 '22 23:12

Boaz