Search code examples
cssword-wrap

CSS How to wrap text before last whitespace


I have some div with fixed width containing text in the form 1234 days ago (10/10/1900).

The text must wrap the date part (10/10/1900) ONLY if string is too long to stay on the same line

I tried to add a new line before the date and apply the rule white-space: break-spaces; but all string are wrapped

Any other attempts to use overflow-wrap or word-break doesn't work as I wish

Have you some idea? Below I show my example code

.row {
  width: 100%;
  display: flex;
  flex-direction: row;
}

.footer {
  width: 170px;
  height: 100px;
  margin-left: 20px;
  padding: 10px;
  white-space: break-spaces;
}

.wrong {
  background-color: red;
  color: white;
}

.correct {
  background-color: blue;
  color: white;
}
<div class="row">
<div class="footer wrong">1234 days ago (10/10/1900)</div>
<div class="footer correct">4 days ago (04/05/2050)</div>
</div>
<p class="wrong">The text "(10/10/1900)" must be wrapped<p>
<p class="correct">The text "(04/05/2050)" fits the line so isn't necessary to wrap<p>


Solution

  • Put the dates into span elements with white-space set to pre.

    <span style="white-space: pre;">(10/10/1900)</span>
    

    (Note that, if the date is wider than the container's 170px width, it will continue to extend past the box without wrapping.)