Heiko Mamerow

Web development with WordPress

Hovering with inline CSS variables

Recently I had a nice little problem to solve: I need to change a dynamic bunch of inline background images (SVG icons) via CSS. The user should manage the icons in WordPress with custom fields.

Origin code example with static inline background image:

// index.php
<div class="icon-box" style="background: url(<?= get_field('icon') ?>)"></div>

// style.css
.icon-box:hover {
    filter: grayscale(100%)
}

As you can see above every icon is just a div box with an SVG as background image. The user can upload the icon in back end with a custom field. The CSS makes an little hover effect. Nothing special at all.

Just an simple hover effect over an background image.
Just an simple hover effect over an background image.

In the new version the icon should not only have an simple hover effect. The icon file his self should change because the motive is different for the hover.

Unfortunately it is not possible to make hover effects with inline CSS. It needs another way.

My first approach was to try SVG sprite. But this is not an solution here because I have to deal with 2 SVG files for every Icon.

My solution: I just used two CSS variables with the URLs from both icons.

Variables in inline CSS can be used in the external style sheet:

// index.php
<div class="icon-box" style="--icon: url(<?= get_field('icon') ?>); --icon-hover: url(<?= get_field('icon-hover') ?>)"></div>

// style.css
.icon-box {
    background: var(--icon)
}
.icon-box:hover {
    background: var(--icon-hover)
}
The hover loads an new background image.
The hover loads an new background image.

Caniuse?

If you don’t have to care about IE 11. Then CSS variables are your friends.

But if you have to care, then there is another way without variables (and without JavaScript of course):

Duplicate the icon box and layer both on top of each other into an frame. Then on hover change the z-index or hide/show with your external CSS.


Big credits for the funny emojis above:
Emoji One, CC BY-SA 4.0, via Wikimedia Commons
Emoji One, CC BY-SA 4.0, via Wikimedia Commons


Leave a Reply

Your email address will not be published. Required fields are marked *