TransWikia.com

How to correctly write word-break in css?

Stack Overflow Asked by Aiko Schurmann on February 10, 2021

<div class="message-user">user.username</div> 

<div class="message-wrapper">
      <div class="message-content">user.message</div>
</div>

in user.message there will be a message placed that will serve as user input so it can be anything

Now the main problem comes with word wrapping. Either it breaks words in random places so that it stays inside the div or it only breaks words on whitespaces. I need a combination of both. It breaks only on whitespaces unless that 1 word would still be too long and only then it would be allowed to break the word in half in order to place it
so I don't need that

SO I don’t need this
enter image description here

but I need this

.messages .message-wrapper {
  display: flex;
  margin-left: 20px;
  margin-bottom: 15px;
  width: fit-content;
  max-width: 60%;
  border-radius: 25px;
  background-color: gray;
  color: white;
}
.message-wrapper,.message-wrapper-me{
word-break: break-all;
}

this is the css

3 Answers

To sum up your problem, you want to break the word only if it's a very long word.

What you need to do:

  • define which word that should be broken up (for example, by its string length)
  • apply word-break property to the only target word

Since it's a dynamic content, you should use JavaScript to manipulate the string.

Good luck!

Answered by Kouta Nakano on February 10, 2021

You need to use break-word

.box {
  border: 1px solid;
  width: 300px;
  overflow-wrap: break-word;
  overflow: hidden;
  resize: horizontal;
}
<div class="box">
  Loremipsumdolorsitametconsecteturadipiscingelit. Sed pulvinar luctus augue. Cras porttitor nulla non nulla feugiat dignissim. Suspendisse vel tristique odio. Nulla sagittis vestibulum arcu, vitae feugiat augue porttitor at. Mauris fringilla sit amet mauris
  at sollicitudin. Aenean sed ultricies lectus, vitae venenatis risus. Duis iaculis gravida augue, eget finibus massa laoreet sit amet. Mauris varius blandit nunc. Fusce erat felis, venenatis non sem et,
</div>

Answered by Temani Afif on February 10, 2021

Try using word-wrap: break-word in the CSS:

.message-wrapper {
  width:150px;
  word-break: break-word;
  text-align: justify;
}
<div class="message-user">user.username</div>
<div class="message-wrapper">
  <div class="message-content">The longest word in English, according to the Oxford English Dictionary, is pneumonoultramicroscopicsilicovolcanoconiosis - a chronic lung disease caused by the inhalation of fine silicate or quartz dust.</div>
</div>

Answered by sbgib on February 10, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP