Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to break a long word inside a div, based on the div's parent width?

Tags:

html

css

I want to wrap a long word inside a div that passes the border of the div's parent into a new line.

I have tried the .wordwrap solution from this Accepted Answer, but it doesn't solve the problem.

Here is what I have tried:

#parent {
  width: 500px;
  height: 500px;
  border: solid 1px;
  position: relative;
}
#child {
  top: 20px;
  left: 300px;
  border: solid 1px;
  position: absolute;
}
.wordwrap {
  white-space: pre-wrap;
  /* CSS3 */
  white-space: -moz-pre-wrap;
  /* Firefox */
  white-space: -pre-wrap;
  /* Opera <7 */
  white-space: -o-pre-wrap;
  /* Opera 7 */
  word-wrap: break-word;
  /* IE */
}
<div id="parent">
  <div id="child" class="wordwrap">
    asfasfafafsafafasfasfafafasfadvaavasdvavdvsavsvasvsvs
  </div>
</div>

Here is the JsFiddle: https://jsfiddle.net/yusrilmaulidanraji/otps5c66/5/

like image 652
Yusril Maulidan Raji Avatar asked Sep 23 '16 09:09

Yusril Maulidan Raji


People also ask

How do I split a word in a div?

Use word-wrap:break-word; It even works in IE6, which is a pleasant surprise. word-wrap: break-word has been replaced with overflow-wrap: break-word; which works in every modern browser.

How do you break a large word in CSS?

The word-break property in CSS is used to specify how a word should be broken or split when reaching the end of a line. The word-wrap property is used to split/break long words and wrap them into the next line. word-break: break-all; It is used to break the words at any character to prevent overflow.

How do you break a long text in CSS?

Breaking long words The word-wrap property is now treated by browsers as an alias of the standard property. An alternative property to try is word-break . This property will break the word at the point it overflows.

How do I wrap a long text in a div?

If you've faced the situation when you need to wrap words in a <div>, you can use the white-space property with the "pre-wrap" value to preserve whitespace by the browser and wrap the text when necessary and on line breaks. Also, you'll need the word-wrap property.


1 Answers

You don't need all those white-space

Instead use

.wordwrap { 
  word-break : break-all;
}

#parent {
  width: 500px;
  height: 500px;
  border: solid 1px;
  position: relative;
}
#child {
  top: 20px;
  left: 300px;
  border: solid 1px;
  position: absolute;
}
.wordwrap {
  word-break: break-all;
}
<div id="parent">
  <div id="child" class="wordwrap">
    asfasfafafsafafasfasfafafasfadvaavasdvavdvsavsvasvsvs
  </div>
</div>

You can also use

word-break : break-word

Check this Answer to see the difference

like image 153
Weedoze Avatar answered Sep 21 '22 13:09

Weedoze