Limit text length to n lines using CSS
Posted by SceDev
Last Updated: February 19, 2024

Want to limit the length of a text to n lines using CSS?

The example below demonstrate how to do that by limiting text to 2 line. You can change the 2 to whatever number of lines you want.

This technique is often used in scenarios where text needs to be truncated after a certain number of lines, such as in news article previews, product descriptions, or anywhere you need to limit the display of text to a certain number of lines.

Before:

After:

 

HTML:

<!doctype html>
<html>
<head>
    <link rel="stylesheet" href="index.css">
<title></title>
</head>
<body>

    <div>
        
      <p class="truncate-text">
       
       Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed euismod ultrices massa, et scelerisque ipsum blandit non. Nullam commodo convallis lorem, sed tempus diam convallis in. Donec interdum, nulla id feugiat consequat, mi ligula tristique tellus, at luctus enim orci non risus. Donec posuere, mauris mattis commodo feugiat, nulla dolor varius lacus, et fermentum lorem ipsum a metus. Donec aliquam est ac metus suscipit, in posuere nisl blandit. Sed in commodo metus, vitae consectetur neque. Fusce pretium convallis mi vitae viverra. Pellentesque.

      </p>
      
    </div>
</body>
</html>

 

CSS:

.truncate-text {
  display: -webkit-box;
  -webkit-line-clamp: var(--line-clamp, 2);  /* Replace 2 with the number of lines you want. */
  -webkit-box-orient: vertical;
  word-break: var(--word-break, 'none');
  overflow: hidden;
  hyphens:auto;
  text-align: var(--align, left);
  --is-single-line: 1 - Clamp(0, Calc(var(--line-clamp) - 1), var(--line-clamp));
  --delay: Calc(-1s * (var(--is-single-line, 1) - 1));
  animation: states 1s var(--delay) paused;

  @keyframes states {
      0% {
          word-break: break-all;
      }
  }
}

div {
  height: 200px;
  width: 400px;
  background-color: powderblue;
}