Have you ever seen your icons flicker or move when your page loads? This happens because the browser loads the icon font a little later, making things shift around. Here’s how to keep the icons in place and make them appear smoothly.
Why Does This Happen?
Material Icons and Symbols use web fonts, which don’t load right away. Instead, the browser:
- Leaves a blank space or shows temporary text where the icon should be.
- Loads the font in the background.
- Puts the icon in place once the font is ready, causing a sudden change.
Some people use visibility: hidden;
to hide icons until they load, but this makes them disappear completely and causes layout changes. Instead, using opacity: 0;
keeps the space reserved so the page looks smoother.
The Fix: Use opacity
Instead of visibility
1. Update Your CSS
Change your CSS to use opacity: 0
so that the icons are invisible at first but don’t move things around:
/* Icons are hidden but still take up space */
.material-icons-outlined,
.material-symbols-outlined {
opacity: 0;
transition: opacity 0.2s ease-in-out;
}
/* Fade them in once the page is ready */
.material-icons-loaded .material-icons-outlined,
.material-icons-loaded .material-symbols-outlined {
opacity: 1;
}
2. Update Your JavaScript
Once the page loads, add a class to make the icons visible:
document.addEventListener("DOMContentLoaded", function () {
document.body.classList.add("material-icons-loaded");
});
This makes the icons fade in smoothly instead of appearing suddenly.
Why This Works
Method | What Happens |
---|---|
visibility: hidden; |
The icon disappears completely, which can cause things to move. |
opacity: 0; |
The icon stays in place but is invisible at first, preventing movement. |
Using opacity
means your icons won’t suddenly pop in and push things around.
Bonus Tip: Load the Font Faster
To make sure icons appear even faster, you can preload the font so the browser gets it earlier:
<link rel="preload" href="/static/material_fonts/icons/material_icon.woff2" as="font" type="font/woff2" crossorigin="anonymous">
<link rel="preload" href="/static/material_fonts/symbols/material_symbols.woff2" as="font" type="font/woff2" crossorigin="anonymous">
This helps the browser load the font before it’s needed, reducing the delay.
Conclusion
By using opacity: 0
instead of visibility: hidden
, you can stop your icons from shifting around when they load. This small trick makes your page look better and feel smoother.
Try it out and see the difference!
Top comments (0)