Home > Software engineering >  How to break a line of words after specific word using css or Javascript
How to break a line of words after specific word using css or Javascript

Time:02-24

I have a String, which I am displaying in one span.

<div>
 <span>The name of this person is john He is a cricket player </span>
</div>

here it is taking the width as of the text is . Now, I don't want to give any specific width to this element. So I tried

.parent{
  display: inline-block // so that the div should take only that width as of the text
}

.childspan {
  //word-wrap: break-all;
}

So, How do I break the span in two lines using CSS after specific word is ?

Is there any way to do this ? without giving the fixed width ?

CodePudding user response:

The easiest thing with js would be

const child = document.querySelector('.parent .child');
child.innerHTML = child.innerHTML.replace("is", "is<br/>");

and it can be used in any element to break after word, also if you need to break after every is, then use it with RegExp

child.innerHTML = child.innerHTML.replace(/is/g, "is<br/>");

CodePudding user response:

You could use 2 span elements and add a <br> in between:

<div>
 <span>The name of this person is john He is</span>
 <br>
 <span>a cricket player </span>
</div>

Or alternatively use the ::after pseudo class:

<div>
 <span id="line1">The name of this person is john He is</span>
 <span>a cricket player </span>
</div>

<style>
#line1::after{
    content: "\a";
    white-space: pre;
}
</style>

CodePudding user response:

U can use <br> tag, where u want to break a line.

  • Related