Font icon size relative to container

Yes, I know, nobody uses font icons anymore. Unless you have to. 😜

Imagine, you some responsive square tiles on your website. You never know, which exact size they have, but you want to place an icon inside them that always has the optimal size.

Screenshot of three squares with vector icons inside of them.

This would be pretty easy, if the icon would be an <img> or an inline <svg>. You could set the width or the height of the inner element to 100% and would be done.

But unfortunately, I did not have an image or SVG, but the good old icon font. I do not want to discuss here, why this project still has them. But I would like to show my solution how I managed to set a dynamic font size, depending on the tile's actual size.

First of all, I created this HTML code:

<div class="tile">
	<span class="my-icon" aria-hidden="true"></span>
</div>

Setting the font size to any rem, em or px value would have a nice result in exactly one screen size, but would not solve my problem. But I'm very happy, all modern browsers support container query units.

To be able to use the container query units, I needed to make my .tile a container:

.tile {
	container: mycontainer / inline-size;

	/* ... some more rules for size and stuff ... */
}

After that, I defined the font size for the <span> inside the container, based on the container. Unfortunately, I was not able to write this rule without a media query. But (min-width: 1px) did the job to match all scenarios.

@container mycontainer (min-width: 1px) {
  * {
    font-size: 80cqw;
  }
}

I have also created a demonstration on codepen.io where you can see the code in action and where you can try around and resize the window.