Explain Codes LogoExplain Codes Logo

How to change the size of mat-icon on Angular Material?

javascript
responsive-design
css-variables
viewport-units
Anton ShumikhinbyAnton Shumikhin·Sep 10, 2024
TLDR

To resize a mat-icon, adjust the font-size in your CSS:

.icon-2x { font-size: 2em; /* Presto change-o! Icon size is doubled! */ }

Then, tag your mat-icon with the new CSS class in your HTML:

<mat-icon class="icon-2x">home</mat-icon>

This way the size will be double using 2em, or set any other scalar value for custom relative sizing.

Scaling icons with transform property

If you find that font-size is too basic for your stylistic ambition, you can have more direct control using the transform CSS property.

Implementing transform for scaling

With the transform: scale(VALUE); style rule, mat-icon can be set to any size designated by VALUE:

.icon-big { transform: scale(2); /* Icon just got hit with a growth ray! */ }
<mat-icon class="icon-big">sms</mat-icon>

The scale() function modifies both the width and height dimensions, while keeping the integrity of the icon intact.

Font-size: a word of caution

The font-size property can produce inconsistent results with mat-icon, depending on the complexity of the icon design. Hence, it's better to trust the scale() function for reliable scaling.

Styling icons with class

Organize your styles by assigning a class to your mat-icon. This would make your CSS target its styles more accurately:

<mat-icon class="custom-size-icon">mail</mat-icon>

Then, match this in your CSS:

.custom-size-icon { transform: scale(2); /* Now, the mail icon size is as big as your unread emails list! */ }

Watch your step: Icon displacement

Note that incorrect adjustments in CSS could lead to icon misalignment. It's always advisable to check the scaled icon's position post scaling.

Advanced Strategies for Mat-icon Styling

Here are some advanced strategies for a more tailored and maintainable approach to Mat-icon styling.

Dynamic Scaling with Viewport Units

Viewport units (vw/vh) can be used for dynamic scaling that adjusts the icon size relative to the viewing area:

.icon-responsive { transform: scale(0.5vw); /* A view to a scale! */ }

Efficiency with CSS Variables

Setting CSS custom properties (variables) can be a time-saver and also makes your code tidy:

:root { --icon-scale-large: 2; } .icon-variable { transform: scale(var(--icon-scale-large)); /* Variable wattage! */ }

Overflow Concerns

When scaling up, ensure icons don’t flow beyond their containers. You might need to wiggle the viewBox attribute or adjust the container dimensions.