Home > Software design >  Is there a property like word-wrap or overflow-wrap that can force breaks at word boundaries?
Is there a property like word-wrap or overflow-wrap that can force breaks at word boundaries?

Time:12-12

For example, If I have a sentence like the following:

I like cute dogs because they're awesome

doing something like word-break: break-word might give you

I like cute dogs because they're awe

some

The behavior I want is for it to break like

I like cute dogs because they're

awesome

I can't seem to find a way to do this. In most cases, the words do seem to fit efficiently into the container, but there are weird cases with long words that spill out even though I would think it should know how to rearrange them for this not to happen. The words aren't even close in length to the width of the container, so it's not that what I'm trying to achieve is impossible or anything. The CSS I have written is so negligible that it's probably not even worth including, but it's something like:

.someClass {
   margin-bottom: 2rem;
   padding: 0.5rem;i 
}

p {
   font-size: 1.1rem;
   margin-bottom: 0.375rem;
}

.someClass's size is a fixed value, and its parent is a flex container. I tried adjusting the available space of the flex cell it occupies to exactly the size of the contained element but it made no difference.

  1. Why do words which are only a fraction of the width of the parent overflow sometimes? Like, why aren't they auto arranged to divide the space without overflowing?
  2. Is there a way to ensure no overflow but without breaking mid-word, and instead breaking at word boundaries

Thanks for the help and cheers.

CodePudding user response:

if i understood you correctly word-wrap: break-word; does what you need

p {
  width: 260px;
  background-color: green;
  word-wrap: break-word;
}
<p>
  I like cute dogs because they're awesome
</p>

CodePudding user response:

You could use the property overflow-wrap: break-word to start the word in another line. Code snippet below:

.container {
 padding: .5rem;
 overflow-wrap: break-word;
 background: yellow;
 width: 100px;
}
<div >
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Egestas tellus rutrum tellus pellentesque eu tincidunt.
</div>

CodePudding user response:

You could use this

.someClass p {
  word-break: normal;
}

or

.someClass p {
   word-break: normal;
   overflow-wrap: anywhere;
}
  • Related