hn.today

Better Icon and Label Alignment

ishadeed.com24 points5 comments
Screenshot of Better Icon and Label Alignment

This explains a common UI issue: list items with icons that look fine when labels are one line but misalign when labels wrap. Using display:flex and align-items:center centers the icon in the container, which looks wrong when text spans multiple lines; switching to align-items:start pins the icon to the container top and reveals font-driven whitespace in the text element. Manually translating the icon with a fixed translateY can visually align one combination of font size, icon size, and container width, but fails when any of those variables change.

The robust solutions handle icons added as HTML elements and as pseudo-elements by making the vertical offset relative to the label's line-height. Compute offset as calc((1lh - var(size)) / 2) and apply transform: translateY(var(offset)) so the icon centers with varying font-size, icon-size, and wrapping. For pseudo-element icons also use background-size: contain, flex-shrink: 0, height: auto, and aspect-ratio: 1 to preserve shape while the container stretches. The practical takeaway: combine flexbox with the lh unit, calc(), aspect-ratio, and height:auto to achieve consistent icon-to-first-line alignment across responsive changes.

Read on ishadeed.com5 comments on Hacker News

Summary generated by AI from the linked article. hn.today is not affiliated with Hacker News or Y Combinator.

More in Web

The daily digest

Today's best Hacker News stories, summarized and screenshotted, one email a day.