CSS HTML

How to limit text display by amount of characters with CSS

December 5, 2021

How to limit text display by amount of characters with CSS

In this article we’ll learn how to limit text display by amount of characters with CSS, so you can easily summarize your text in HTML.

limit text display by amount of characters cover

Hey you programmer, how are you? Let’s learn how to summarize text with CSS!

Usually, this function is done on backend or even JavaScript, but the good news is that it is perfectly possible to do this with CSS

First, we must determine a measure of the text, as we cannot specify the number of characters, but we can use the measure ch for that, which will have almost the same proportion.

Then we use overflow with hidden to hide the characters above this measure

And to give the effect that the text continues, that is, insert the ellipses

We can put a text-overflow rule with the value of ellipses

Eliminate white-space with “nowrap”, so the text doesn’t break lines

Let’s produce an example:

<!DOCTYPE html>
<html>
 <head>
  <title>Limitar exibição de texto por quantidade de caracteres com CSS</title>
  <meta charset="utf-8">
 </head>
 <body>
  <p>Este texto será resumido em poucos caracteres apenas com CSS</p>
 </body>
</html>

And now the CSS to summarize the text:

p {
 max-width: 25ch;
 overflow: hidden;
 text-overflow: ellipsis;
 white-space: nowrap;
}

And the return in the browser:

Note that now the text was summarized only with CSS, thus achieving the objective of the article.

Conclusion

In this article we learned how to limit text display by amount of characters with CSS

We used a width in ch to limit the text size, then to hide the excess it was applied the overflow property set on hidden

Finally, we add an ellipsis to the text with the text-overflow rule

In addition, the white-space rule with nowrap served for the text not to break lines

Want to learn more about CSS? Click here!

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x