Limit text length to N lines with CSS

TABLE OF CONTENTS
During web development, sometimes we need to limit the text length or limit the number of lines displayed in a paragraph of text.
One of the common methods to limit the number of lines displayed in a paragraph of text is to use attributes -webkit-line-clamp
. This property allows us to specify the maximum number of lines the text should display.
To use this method, we need to specify the following properties for the text element we want to limit:
div {
display: -webkit-inline-box;
overflow: hidden;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
}
display: -webkit-inline-box
: Converts the text element to an inline-box. This helps ensure that the text will be displayed in a single line.overflow: hidden
: Hides cut off lines of text.-webkit-line-clamp: 2
: Specifies the maximum number of lines the text should display. Specifically, here are 2 lines.-webkit-box-orient: vertical
: Converts an inline-box to a vertical box. This helps ensure that the text will be displayed vertically.For example, limit text paragraphs to <div>
there are two lines. If the text is longer than 2 lines, it will be cut and inserted before the 3 dots "...".
See the Pen Limit text length to N lines by ARTRU (@artrublog) on CodePen.
This method is very simple and easy to use.
This method can be used to limit the number of lines displayed in any piece of text, regardless of the width or height of that text element.
Properties -webkit-line-clamp
Not fully 100% compatible across browsers. However, major browsers still support it.
This method may not work correctly on browsers with small default font sizes.
Method -webkit-line-clamp
is an effective method to limit the number of lines displayed in a paragraph of text. This method is relatively simple and easy to use, and can be applied to any text element.
Related Articles