How to create icons correctly aligned with the text

Diario del capitán, fecha estelar d116.y40/AB

There's a pretty shitty annoying problem with icons when working alongside text. It's called alignment.

Electric sign - Photo by Brittney Burnett

The CSS box model does not contemplate that an element generated with a width and a height can be part of the line spacing, so they do not end up centring well without cheating.

Nor have I found any property allowing inheritance of the height as interpreted by the text from a custom element.

To understand the problem, we can see these two images. What's in blue corresponds to the line-height.

First the icon element:

HTML code

And now, the text label itself:

HTML code

As you can see, they're not exactly aligned, and while for a lot of people this is acceptable, we always look for pixel-perfect designs.

To solve this misalignment, we create the icon using text with a before, so we don't have to specify either width or height, and it can continue to be inline. To simulate the icon, we use the letter M, which is the letter used for spacing in the designs.

In this way, being a text element, it sits correctly on the baseline, and we can replace it without problems with the mask. We have not found a better solution, but I'm sure there has to be something better than using a before and duplicating the selectors.

For future projects, we will create the icon selector and another selector to specify the icon to use, which is going to be a more elegant solution. In the meantime, you can use this solution to get this out of the way!

HTML code

The code is the following:

    .icon {
      display: inline;
      background-color: currentColor;
      mask: var(--icon) center/contain no-repeat;

      &::before {
        content: "M";
Javier Artero

Javier Artero

Javier es un diseñador web experimentado que ha pasado años enseñando las maravillas del desarrollo frontend y el diseño. Sus principales aficiones son añadir animaciones CSS en todas partes y jugar a Overwatch.

comments powered by Disqus

Estás a un paso de conocer a tu mejor socio.