简体   繁体   English

如何在 css 中正确写断字?

[英]How to correctly write word-break in css?

<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在 user.message 中将放置一条消息作为用户输入,因此它可以是任何东西

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.它要么在随机位置打断单词,使其留在 div 内,要么只打断空格上的单词。 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它只在空格处中断,除非 1 个单词仍然太长,然后才允许将单词分成两半以便放置所以我不需要那个

SO I don't need this所以我不需要这个在此处输入图像描述

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这是 css

Try using word-wrap: break-word in the CSS:尝试在 CSS 中使用word-wrap: break-word

 .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>

You need to use break-word你需要使用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>

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.由于它是动态内容,因此您应该使用 JavaScript 来操作字符串。

Good luck!祝你好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM