Utilizing icons in user interface elements is helpful. In addition to element labeling, icons can help reinforce a user element’s intention to users. But I have to say, I notice a bit of icon misalignment while browsing the web. Even if the icon’s alignment is correct, icons often do not respond well when typographic styles for the element change.
I took note of a couple real-world examples and I’d like to share my thoughts on how I improved them. It’s my hope these techniques can help others build user interface elements that better accommodate typographic changes and while upholding the original goals of the design.
I found this messaging example on a popular media website. The icon’s position doesn’t look so bad. But when changing some of the element’s style properties like and , it begins to unravel.
We want our icon’s top edge to be at the blue dashed line, but we often find our icon’s top edge at the red dashed line.
Have you ever inserted an icon next to some text and it just won’t align to the top of the text? You may move the icon into place with something like . This works well enough, but if typographic styles change in the future, your icon could look misaligned.
We can position our icon more reliably. Let’s use the element’s baseline distance (the distance from one line’s baseline to the next line’s baseline) to help solve this.
We’ll store that in a CSS custom property:
We can then move our icon down using the result of (baseline distance – font size) / 2.
With a of () and of , our icon will be moved 4 pixels.
The second example I found is an unordered list. It uses a web font (Font Awesome) for its icon via a pseudo-element. There have been plenty of great articles on styling both ordered and unordered lists, so I won’t go into details about the relatively new : pseudo-element and such. Web fonts can generally work pretty well with icon alignment depending on the icon used.
Because we’ll also use a pseudo-element in our solution, we’ll leverage positioning. This example’s icon size was a bit larger than its adjacent copy (about 2x). Because of this, we will alter how we calculate the icon’s position. The center of our icon should align vertically with the center of the first line.
Move the icon down using the result of (baseline distance – icon size) / 2.
So with a of (), a of , and an icon sized 2x the copy (), our icon will get get a top value of -3.2 pixels.
With a larger of (), of , and icon, our icon will get get a top value of -12.8 pixels.
For user interface icons, we have a lot of options and techniques. We have SVGs, web fonts, static images, , and . One could even use background-colors and clip-paths to achieve some interesting icon results. Performing some simple calculations can help align and scale icons in a more graceful manner, resulting in implementations that are a bit more bulletproof.
See also: Previous discussion on aligning icon to text.