I ran into an issue while implementing customisable text sizes into a UI. I had a Callout
component which consists of a box containing an icon and a block of text – a layout similar to this:
This component was built a few years ago and designed so the icon perfectly centered on the first line of text. When the text wrapped onto multiple lines it would still remain centered on the first line. I achieved this using flex box and aligning the items to the top. The icon was “cleverly” sized and positioned to fit the first line. Optically it was great, but it was not flexible at all.
<ps-callout>
<ps-icon name="dashboard"></ps-icon>
<div>Some callout text here</div>
</ps-callout>
ps-callout {
display: flex;
align-items: start;
gap: 10px;
}
All was good, until I changed the font size which proportionally adjusted the line height. This meant that with the current styles I could only center either on 1 line of text, or the first line of multiple lines of text. It wouldn’t work in both cases. I needed the icon to adjust as the line height adjusted with the font size.
The CSS lh
unit
I vaguely remembered hearing about a new CSS unit called lh
which would enable sizing relative to the current line height. I was happy to find that all recent browsers support the lh
unit. After some tests I found that this unit was indeed going to solve my problem.
Centering and scaling with font size
If you set the icon width and height to 1lh
, the icon will always scale to fit the text line. You can then use scale
to further adjust the icon size if you needed it to be slightly larger than the line height but not take up more space.
ps-callout > ps-icon {
width: 1lh;
height: 1lh;
scale: 1.2;
}
Now regardless of the font size, the icon will always scale and align with the first line of text.
Centering with a fixed size
If you needed the element to remain the same size, then you could wrap the icon and apply the lh
sizing to the wrapper, then center the icon inside the wrapper.
<ps-callout>
<div class="callout-icon">
<ps-icon name="dashboard"></ps-icon>
</div>
<div>Some callout text here</div>
</ps-callout>
ps-callout > .callout-icon {
width: 1lh;
height: 1lh;
display: flex;
align-items: center;
justify-content: center;
}
ps-callout ps-icon {
width: 16px;
height: 16px;
}
Demo
See the Pen Untitled by Ben Foster (@benfoster) on CodePen.
You must be logged in to post a comment.