Limit text length to n lines using CSS

Using CSS, it is possible to limit the text length to N lines using CSS. This concept is known as line clamping or multiple line truncating. Here, we will learn how we can limit text length to n lines using the line-clamp property.
By Apurva Mathur Last updated : July 15, 2023

How to limit text length to n lines using CSS?

The best solution to this problem is using the line-clamp property of CSS. The line-clamp property shortens text at a specific number of lines. It is defined as shorthand for max-lines and block-overflow.

Syntax

.line {
  line-clamp: [none|<integer>];
}

The combination of line-clamp property with overflow-hidden value helps to limit the text length.

Example

Lets us see via an example:

<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="UTF-8">
      <title>Title</title>
   </head>
   <style>
      .line {
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 1; /* number of lines to show */
      line-clamp: 1;
      -webkit-box-orient: vertical;
      }
      .block{
      height:40%;
      width:20%;
      background-color: #b3d4fc;
      }
   </style>
   <body>
      <div class="block">
         <h2>BLOCK</h2>
         <p class="line">You must be the change you wish to see in the world." - Gandhi. "Live for what's worth dying for, and leverage technology to create the world you wish to see</p>
      </div>
   </body>
</html>

Output:

Example 1: Limit text length to n lines

As we can see the text line is limited to 1 in the example. If we want to change this limit we can directly do it by changing the following values according to our preference.

-webkit-line-clamp: 5;
line-clamp: 5;

Output: After replacing the values in the code

Example 2: Limit text length to n lines

Note: -webkit-line-clamp, line-clamp the value which you are assigning should be the same for both.

CSS Examples »




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.