© 2024 fjorge. All rights reserved.
Fixing Blurry Logos and Background Images
As retina screens and HD monitors are becoming more common developers must account for higher resolution images and icons. Given the wide range of support for newer formats it can be difficult to load the latest and greatest assets while maintaining backwards compatibility. Loading a standard definition image will look grainy or blurring on HD monitors, but loading a .svg on an old machine will fail to show up at all. That said, here are 2 solutions to quickly fit your needs:
Image Tags using JavaScript
Using javascript and the onerror
event we can look for a higher resolution .svg image in the src attribute, but if that fails to load we can call a function to look for a supported fallback image.
HTML:
<img src="logo.svg" onerror="this.onerror=null; this.src='logo.png';" alt="Site Logo" />
Background Images using CSS
One tool that helps immensely with newer css support is Modernizr. Modernizr detects features that are available on your user's browser and adds classes to the <html>
tag that make it easy for developers to target attributes where available. For full instructions on setting up Modernizr you can read about it here, but for now we're just going to use it to add .svg images for logos and icons.
Depending on your setup, once the Modernizr script is referenced in the <head>
of your html, your opening tag will look something like this:<html class=“flexbox video svg inlinesvg cssgradients borderimage borderradius boxshadow textshadow”>
You can see now that we have a class 'svg' that applies to our site which we can use to load an alternative icon as needed, but also maintain a widely supported fallback for browsers and devices that don't support the desired format. Set the basic image as the background on your element, in this case we're targeting a div with the class 'background-icon'. Then prefix your selector with .svg
and browsers that have that class applied to the site will load the svg icon.
CSS:
.background-icon {background-image: url(image-src.png);}
.svg .background-icon {background-image: url(image-src.svg);}