Yann
Yann

Reputation: 39

Adjust width <p> for having a specific number of lines on display

I'm trying to find a way to adjust the width of some specific paragraph elements, in order to have automatically two lines, with the same width.

Even if there is more text, the width will be adjusted, for having two equal lines (the latest line should not be wider than the first one).

I tried by fixing the width of the paragraph with CSS, but it could work only if I have the same text...

Do you know if there is a jQuery plugin for that, or an existing code I could re-use ?

having same width paragraph, calculated with text

Upvotes: 0

Views: 70

Answers (1)

joohong89
joohong89

Reputation: 1271

Here's my take.

For the line break, I would add a <br>to my text.

The position I would add <br> would be the first space after n/2. Thus the second line will always be shorter than first one.

The following is a rough example, which you might need to refine further.

var textElement = $('p');

textElement.each(function(){
  var text = $(this).text();
  var length = text.length;
  

  for(var i =(Math.ceil(length/2)); i<length; i++){
     if(text[i]===' '){
        var text2 = text.slice(0, i) + "<br>" + text.slice(i);
        $(this).html(text2);
        break;
     } 
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse ac lectus ac 
</p>


<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
</p>

<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse ac lectus ac elit vestibulum ultricies eget sit amet lacus. Lorem ipsum dolor sit amet.
</p>

Upvotes: 1

Related Questions