javahtmlcsswebmern

Shrink / collapse overflowing text


Please check the attached image. As you can see, text is overflowing outside the div. I just want to collapse the overflowing text and display "Read more" in the end. While user click "read more" text should be expanded.

I'm working on a next js project.

Screenshot of div

My requirement is to collapse the text to specified lines not to break the text from specified lines.


Solution

  • Create a Card component like this:

    export default function Card() {
      const [expand, setExpand] = useState(false);
      
      return (
        <div>
          <div className={`${style.collapsible_text} ${expanded ? '' : style.collapsed}`}>
            {/* Card text goes here */}
          </div>
          <p onClick={() => setExpand(!expand)}>{expand? "read more..." : "read less..."</p>
        </div>
      );
    }
    

    Then, apply the following css to the Card component:

    .collapsible_text {
      max-height: 50px;
      overflow: hidden;
    }
    
    .collapsed {
      max-height: 50px;
    }