Skip to content Skip to sidebar Skip to footer

Word-wrap Doesn't Respect Parent's Width For Long Non-break Text

Ideally , I want each msg to have max-width of 30vw, but at the same time respect parent's width. The first row behaves correctly, but the second row doesn't. If parent's width is

Solution 1:

Simply set max-width:100% to .parent so this one respect the width of .container then rely on flex and your element will shrink by default. Also don't forget min-width:0 on the element itself to enable the element to shrink.

.container {
  width: 300px;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  padding: 1em;
  background-color: blue;
}

.parent{
  display:flex;
  flex-direction:row;
  flex-wrap:nowrap;
  padding:1em;
  background-color:red;
  box-sizing:border-box;
  margin-bottom: 1em;
  max-width:100%; /*Added this */
}
.name{
  background-color:mistyrose;
  width: 70px;
  padding: 1em;
}
.msg{
  background-color:powderblue;
  max-width:30vw;
  min-width:0; /*addedd this*/padding:.5em;
  word-wrap:break-word;
}
<divclass='container'><divclass="parent"><divclass="name">
      David
    </div><divclass="msg">
    How are you? How are you? How are you? How are you? How are you? How are you? How are you? How are you? How are you? How are you? How are you? How are you? How are you? 

    </div></div><divclass="parent"><divclass="name">
      Hannah
    </div><divclass="msg">
    somethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomething

    </div></div></div>

Solution 2:

If you do not need to support IE11 or safari, a simple solution would be to switch your word-wrap:break-word; with word-wrap: anywhere (working example)

If you need to support safari (but still not IE11), then instead replace word-wrap:break-word; with word-break: break-word. Note that word-break: break-word is deprecated in favour of word-wrap: anywhere.

I would also recommend switching word-wrap for its more commonly used alias: overflow-wrap. It will be more effective when used in a search term.

Also see: Difference between overflow-wrap and word-break?

Solution 3:

Just add :

word-break: break-all;

in .msg

Post a Comment for "Word-wrap Doesn't Respect Parent's Width For Long Non-break Text"