Home > OS >  Css break every 2 words
Css break every 2 words

Time:09-02

How to break every 2 words with css and make it responsive for each possible word

Example:
The community is here -> 
The community
is here

CodePudding user response:

I would not suggest using CSS in this case.

Example of how you could achieve it with regex:

let text = 'The community is here';
// Regex for linebreak after each second space.
let lineBreakText = text.replace(/^((\S \s ){1}\S )\s /, '$1<br>');
let element = document.getElementById('example');
element.innerHTML = lineBreakText;
<div id="example"></div>

S matches one or more non-space characters. \s matches one or more space characters. It will add a <br>tag for each second word.

CodePudding user response:

Assuming that your text is in an html paragraph tag <p> , you can put the paragraph inside a <div> and limit the width of the div.

Example below :

<div style ="
  width:110px;
">
<p>
  The community is here
</p>
</div>

Playground here

  • Related