How to limit the length of text in a paragraph [duplicate]
Asked Answered
A

1

25

I have a paragraph as below, which may be of any length:

Breaking India: Western Interventions in Dravidian and Dalit Faultlines is a book written by Rajiv Malhotra and Aravindan Neelakandan which argues that India's integrity is being undermined.

I want it to appear as:

Breaking India: Western Interventions in Dravidian and Dalit Faultlines is a book written by Rajiv Malhotra...

below is the code which populates description in my website:

currently description goes to any no. of line based on product, i need to limit this to 3 lines.

Astatic answered 30/1, 2014 at 3:29 Comment(4)
Show some code, please?Tetrahedron
See jsfiddle.net/tewathia/89d22/1Eu
@Eu - i want it to be trimmed by default to some text length. button click is not required. how to achieve that?Astatic
The button click was only for demonstration, you can trim the text-length automatically by simply running the btn.onclick function code on pageload, para.innerText = para.innerText.substr(0, 100) + '...';Eu
P
46

If you want to use html and css only, your best bet would probably be to use something like:

p {
     width: 250px;
     white-space: nowrap;
     overflow: hidden;
     text-overflow: ellipsis;
}

Here is an example: http://jsfiddle.net/nchW8/ source: http://css-tricks.com/snippets/css/truncate-string-with-ellipsis/

If you can use javascript you can use this function:

function truncateText(selector, maxLength) {
    var element = document.querySelector(selector),
        truncated = element.innerText;

    if (truncated.length > maxLength) {
        truncated = truncated.substr(0,maxLength) + '...';
    }
    return truncated;
}
//You can then call the function with something like what i have below.
document.querySelector('p').innerText = truncateText('p', 107);

Here is an example: http://jsfiddle.net/sgjGe/1/

Pinguid answered 30/1, 2014 at 4:5 Comment(2)
wanted to do it only in css and html but facing difficulty in doing it for multiline, hence deciding to use above javascript code.Astatic
if you want to limit using characters only p { max-width: 250ch; }Carson

© 2022 - 2024 — McMap. All rights reserved.