Home > Net >  How to limit characters in Typography of MUI?
How to limit characters in Typography of MUI?

Time:09-30

My titles are very long I want them to look like this:

This is a title of...

This is my code

<CardContent>
 <Typography gutterBottom variant="h5" component="div">
   <Link href={`/${encodeURIComponent(data.slug)}`}>
     <a>{data.title}</a> // This is a string of title text
   </Link>
  </Typography>
</CardContent>

How to limit them to 18 characters only and add ... at the end?

CodePudding user response:

Usually you solve this with CSS. Set a max-width together with text-overflow: ellipsis;.

The advantage is better SEO and the browser is able to use the available space more efficiently than just counting characters.

For example a M character is larger than a l character.

But you can also limit it with JS:

<CardContent>
 <Typography gutterBottom variant="h5" component="div">
   <Link href={`/${encodeURIComponent(data.slug)}`}>
     <a>{data.title.length <= 18 ? data.title: (data.title.substr(0, 18)   "...")}</a> // This is a string of title text
   </Link>
  </Typography>
</CardContent>

CodePudding user response:

You can use simple custom css to limit this

span {
    display: inline-block;
    width: 200px;
    white-space: nowrap;
    overflow: hidden !important;
    text-overflow: ellipsis;
}
<span>
rem ipsum dolor sit amet, consectetuer adipiscing elit. Nullam lectus justo, vulputate eget mollis sed, tempor sed magna. Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Proin pede metus, vulputate nec, fermentum fringilla, vehicula vitae, justo. Donec vitae arcu. Nullam eget nisl. Etiam commodo dui eget wisi. Praesent vitae arcu tempor neque lacinia pretium. Aenean fermentum risus id tortor. Proin mattis lacinia justo. Integer vulputate sem a nibh rutrum consequat. Nullam justo enim, consectetuer nec, ullamcorper ac, vestibulum in, elit.
</span>

  • Related