Reputation: 48166
Using CSS, how can I size a box's height in terms of its (or its parent's) line-height?
This would allow easily making regions of text an exact multiple of a number of lines, e.g. to allow showing exactly three lines.
I don't want a javascript solution as those are generally slow and interact poorly with dynamically re-rendered layouts.
Edit: The line-heights in my case are specified in unit-less numbers, as recommended on MDN, so it'd be handy if line-height units weren't required to get this to work.
Upvotes: 13
Views: 8677
Reputation: 1134
The Level 4 spec for CSS values now defines a new unit called lh
. However, it is still not widely supported at the time of writing.
It's also worth mentioning that a rlh
unit is available which behaves the same way as the rem unit.
With this new unit you could do something like this to show only 3 lines of text for example.
.wrapper {
height: 3lh;
overflow: hidden;
}
Upvotes: 14
Reputation: 1231
Here's a workaround I used
<div style="display: flex; border: 1px solid red">
<div>
<br>
<br>
<br>
</div>
<div>
This text will appear in a box that has a height of at least 3 lines.
</div>
</div>
Upvotes: 0
Reputation: 3696
I'm not sure I've entirely understood the question, but couldn't you just use relative units - ems?
If the line height is, for example, 2ems (or unitless) and you want the total height of the box to be 3 "lines" high (presumably not taking into account padding) then you could set the height to be 6ems. This way, the line height is flexible based on your base unit (font size) and the height will also be fluid using the same base unit.
Here's an example:
.myBox {
line-height: 2; // this will be twice the value of the font-size
height: 6ems; // equivalent to 3 lines high
To achieve the same thing in SASS you could write:
$lineheight: 2; // this value can be unitless or a unit like ems, px or percentage
$numberoflines: 3;
.myBox {
line-height: $lineheight;
height: $lineheight * $numberoflines;
}
This would have the flexibility for you to move your variables into a settings file so that you (or someone else) can easily alter the values without having to find all the selectors that use the variables.
Upvotes: 5