Skip to main content
CSS Tip

Count the number of lines inside a text

By adjusting the code of the previous tip (getting the width/height of any element) we can do some intresting counting. For example, we can count the number of lines inside a text.

@property --_y {
syntax: "<number>";
inherits: true;
initial-value: 0;
}
@property --h {
syntax: "<integer>";
inherits: true;
initial-value: 0;
}
body {
timeline-scope: --cy;
}
/* the text container */
.container {
overflow: auto;
position: relative;
}
.container:before {
content:"";
position: absolute;
left: 0;
top: 0;
height: 1lh; /* instead of 1px we use 1lh (the height of a line box) */
view-timeline: --cy block;
}
/* the element that will show the count */
.count {
--h:calc(1/(1 - var(--_y)));
animation: y 1s linear;
animation-timeline: --cy;
animation-range: entry 100% exit 100%;
}
.count:before {
content: counter(h);
counter-reset: h var(--h);
}
@keyframes y {to{--_y:1}}

Here is a static demo:

See the Pen Counting the number of lines inside a text by Temani Afif (@t_afif) on CodePen.

Here is a version where you can edit the content. The number of lines will adjust based on the content you will enter.

See the Pen Dynamic line counting by Temani Afif (@t_afif) on CodePen.

More detail: frontendmasters.com/blog/how-to-get-the-width-height-of-any-element-in-only-css


More CSS Tips