Search code examples
htmlcsswidthword-wrap

Getting desired min-width/line-wrapping behavior


What should I do to get a <div> containing variable text behaving as follows:

  • width is always at least 400px;
  • words are not broken across lines, but lines can be broken at word boundaries;
  • text never overflows the border of the div, i.e. the width stretches to accommodate content such as very long words;
  • width is exactly 400px whenever possible. In particular, if there is a long paragraph with short words, the width should be exactly 400px.

The closest I got was using display: inline-block; min-width: 400px; but long paragraphs with short words still stretch the width.


Solution

  • You're saying you want your div to behave like a table / table-cell.

    This should meet all your stated requirements:

    .box {
      width: 400px;
      display: inline-table; /* table|inline-table|table-cell */
      word-wrap: normal;
    }
    

    Demo: https://jsfiddle.net/cqo9yupw/