Posted in: CSS Tips & Tutorials

Posted on:

Control Text Line Length With Line-Clamp

CSS line-clamp enables sleek management of overflowing text by limiting visible lines in your web designs! This guide will swiftly elevate your UI creation skills, whether you're a beginner or intermediate. Dive in to master text truncation with line-clamp and boost your designs!

The CSS line-clamp property is a handy tool that allows you to limit the number of lines shown from an element, effectively truncating text. It’s often used in conjunction with display: -webkit-box; and -webkit-box-orient: vertical to work properly as it originated from the Webkit browser engine. Remember, since this is a non-standard property, it mainly works with browsers based on Webkit and Blink, like Safari and Chrome.

p {
  display: -webkit-box;
  -webkit-line-clamp: 3; /* Display 3 lines */
  -webkit-box-orient: vertical;
  overflow: hidden;
}
<p>This is an example paragraph with more text than can fit in three lines, so it will be truncated by the line-clamp property.</p>

In this basic example, the paragraph <p> will display only three lines of text, and the remaining text will be hidden.

Intermediate Example:

You can use line-clamp with a responsive design to show a different number of lines based on the screen width.

p {
  display: -webkit-box;
  -webkit-line-clamp: 5; /* Display 5 lines by default */
  -webkit-box-orient: vertical;
  overflow: hidden;
}

@media (max-width: 767px) {
  p {
    -webkit-line-clamp: 2; /* Display 2 lines on screens narrower than 767px */
  }
}

This will show two lines of text by default, but on screens wider than 768px, it will display four lines of text.

Advanced Example:

Let’s create a more complex example involving a class and combining it with other CSS properties for better styling.

.card {
  width: 200px;
  padding: 10px;
  border: 1px solid #ccc;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.card .text {
  -webkit-line-clamp: 5;
}

.card:hover .text {
  -webkit-line-clamp: unset; /* Show all lines on hover */
}
<div class="card">
  <p class="text">This is an example of a more complex scenario where the text is inside a card, and will show all content when hovered over.</p>
</div>

In this advanced example, the text within the .card will be truncated after five lines, but when the user hovers over the card, the line-clamp property is unset, showing all the content.

Remember, even though line-clamp is very useful, it is not a standard CSS property, and it might not work in all browsers, so always test thoroughly. Consider using a JavaScript-based solution or other CSS methods for truncating text for broader browser support.

You may also like these posts.

Join The Community

Join over 13,500 WordPress enthusiasts and become part of a vibrant community.