Search code examples
javascriptcssline-breaks

How can I have text break to new lines at certain points when squished in CSS or JavaScript?


I have a caption on a photo with an author and license (three items). I would like for it to keep the author all on one line, and the license all on one line, if possible, but otherwise wrap the text. Is that possible in CSS somehow, or in JavaScript even in a straightforward way?

Say for example I have a wide screen. This would be my full caption:

A photo of an arctic fox by U.S. Fish and Wildlife Service Southeast Region (Public Domain)

But say the figure was smaller or the screen was smaller. I would be okay with any of these scenarios:

A photo of an arctic fox
by U.S. Fish and Wildlife Service Southeast Region
(Public Domain)

A photo of an arctic fox
by U.S. Fish and Wildlife Service Southeast Region (Public Domain)

A photo of an arctic fox by U.S. Fish and Wildlife Service Southeast Region
(Public Domain)

I would not be okay with this though (where it splits in the middle of one or more of the three):

A photo of an arctic fox by U.S. Fish and Wildlife
Service Southeast Region (Public Domain)

A photo of an arctic fox by
U.S. Fish and Wildlife
Service Southeast Region (Public
Domain)

I basically want it to linebreak around each of the main elements, not inside the elements. Unless the area is just too small to accommodate any of these, then it would be okay to break in the middle of an element, for example in this tiny size:

A photo of an arctic
fox by U.S. Fish and
Wildlife Service Southeast
Region (Public Domain)

That would be okay.

Do I need to write some sort of line break algorithm for this, or is there a way to do word-break: break-word, but word-break: break-around-custom-spans sort of thing? If a CSS solution isn't available, how would this be solved with an algorithm?


Solution

  • If you can edit the string, add \n at the required string.
    Add the white-space CSS property on the parent element.

    const str = "A photo of an arctic fox \n by U.S. Fish and Wildlife Service Southeast Region \n (Public Domain)";
    
    const p = document.createElement("p");
    p.textContent = str
    document.body.appendChild(p);
    p{
      white-space: pre-line;
    }