Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

CSS

Jimmy Mannan
Jimmy Mannan
5,201 Points

Limiting the number of characters in a post and adding 'read more' with html/css

I have a fixed height box containing a post. Since the content will vary, I would like 'read more' to be added once the number of characters in the post has reached a specific number so all the content stays in the box with no scroll bars.

Is this possible with html/css? Thanks

2 Answers

Sergey Podgornyy
Sergey Podgornyy
20,660 Points

No, you need to use JavaScript:

function truncate(str, num) {
  if (num >= str.length ) {
    return str;
  } else if ( num > 3) {
    str = str.substr(0,num - 3) + "...";
  } else {
    str = str.substr(0,num) + "...";
  }
  return str;
}

truncate("A-tisket a-tasket A green and yellow basket", 11);
Jimmy Mannan
Jimmy Mannan
5,201 Points

Thank you Sergey. I guess I will just copy and paste this for now :-)

Sergey Podgornyy
Sergey Podgornyy
20,660 Points

You are welcome. Just for notice, first parameter in function is your text, and second is a limit number - https://jsfiddle.net/n6vdg5w4/