Home > Net >  Word-break at nth word in css
Word-break at nth word in css

Time:10-28

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?

CodePudding user response:

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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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.

CodePudding user response:

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.

CodePudding user response:

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>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  •  Tags:  
  • css
  • Related