Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

I have a caption on a photo with an author and license (3 items). I would like for it to keep the author all on one line, and license all on one line, if possible, but otherwise wrap the text. Is that possible in CSS somehow, or in JS 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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 3):

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 no CSS solution is available, how would this be solved with an algorithm, if you could point me in the right direction.

>Solution :

If you can edit string, Add \n at required string.
Add white-space css property on 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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading