How To Limit Lines Of Text With CSS 'line-clamp' Property 👩🏼‍💻.

ishrat - Nov 30 '23 - - Dev Community

The line-clamp property in CSS is a convenient way to truncate multi-line text and show an ellipsis (...) at the end, limiting the display to a specified number of lines. Here's a quick tutorial on how to use the line-clamp property:






here let's another example -


/* CSS Code */

/* Apply the line-clamp property to the element you want to truncate */
.truncate-text {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  overflow: hidden;
  /* Set the number of lines you want to display */
  -webkit-line-clamp: 3; /* Change '3' to the desired number of lines */
}

/* Add styles for better appearance */
.truncate-text {
  /* Set a specific height for the container (optional) */
  height: 3em; /* Change '3em' to adjust the height */
  /* Ensure proper text wrapping within the container */
  white-space: normal;
}
Enter fullscreen mode Exit fullscreen mode

In this example, the .truncate-text class is applied to the HTML element containing the text you want to truncate. The -webkit-box and -webkit-box-orient properties are used for compatibility with WebKit browsers (such as Chrome and Safari).

The key property is -webkit-line-clamp, where you specify the number of lines you want to display before truncating the text. In this example, it's set to 3. Adjust this value according to your design requirements.

The overflow: hidden property ensures that any overflowing text is hidden, and the white-space: normal property ensures proper text wrapping within the container.

Here's an example of how you can apply this class in HTML:

<!-- HTML Code -->

<div class="truncate-text">
  <!-- Your text content goes here -->
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
</div>
Enter fullscreen mode Exit fullscreen mode

Remember to adjust the class name and the number of lines according to your use case. This method is widely supported in modern browsers but primarily uses the -webkit- prefix for now. Keep an eye on updates and support in other browsers.

That's all for today! Happy Coding 👩🏼‍💻🙋‍♀️.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .