简体   繁体   中英

Word-break at nth word in css

I have a huge sentence as below:

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud ullamco laboris nisi ut aliquip ex ea commodo consequat.

I want to break this huge sentence at every 6th word. so it should look as below:

Lorem ipsum dolor sit amet, consectetur
adipiscing elit, sed do eiusmod tempor
incididunt ut labore et dolore magna 
aliqua. Ut enim ad minim veniam, quis
nostrud ullamco laboris nisi ut aliquip
ex ea commodo consequat.

I tried the following css rules:

word-break: break-all;

No impact. Next I tried:

 overflow: visible;
    width: 0px;

This is breaking every word to be in a line. any help on how i can word-break at 6th word?

As the other answer mentioned, CSS has no way of adding line breaks.

However, there's a lesser known unit in CSS: ch . Depending on the font you use, you might be able to roughly achieve what you want:

 div { width: 32.5ch; }
 <div> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud ullamco laboris nisi ut aliquip ex ea commodo consequat. </div>

If that doesn't work for your use case, a more reliable solution would be to manually add line breaks in your text and then use white-space: pre-wrap to display them, as described in this answer .

You'll probably want to use your second solution, but set the width to be wide enough for roughly 6 words.

overflow: visible;
width: 100px; /* 6 word width */

There's no way to break on 6 words in CSS, the alternative is adding <br /> after every 6th word in JS or some pre-processor.

I know you've mentioned you want it in CSS. But if JS is allowed then its easy without any guesses for width. So this will work even if the world length is big.

See the Snippet below:

 var text = document.getElementById("text").innerText; text = text.match(/(\\S+ ){1,6}/g).join("<br>"); // You can change the number 6 to whatever you want. document.getElementById("text").innerHTML = text;
 <div id="text">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud ullamco laboris nisi ut aliquip ex ea commodo consequat.</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM