Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

On Chrome background images set with CSS custom properties flicker when inside an anchor tag

I am using CSS custom properties to set the background image for a div. The div is nested inside an anchor tag to represent a clickable "card" that routes to another page.

In Chrome with dev tools open and cache disabled, when I click on the card, the background image flickers. It appears to be fetching the image again every time the state of the anchor tag changes.

Additionally, if I add text-decoration to the anchor tag on hover the image flickers when hovering too.

CSS looks like:

:root {
  --image-url: url("https://images.unsplash.com/photo-1529778873920-4da4926a72c2?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80")
}

.image-div {
  height: 100px;
  width: 100px;
  background-image: var(--image-url);
  background-position: 0;
  background-size: cover;
}

See the pen: https://codepen.io/hally9k/pen/RmepVe

like image 528
hally9k Avatar asked May 30 '19 03:05

hally9k


1 Answers

I have found that I can stifle this flickering (and refetching) by ensuring the image is returned with a Cache-Control header. Some common services (e.g. S3) don't return Cache-Control headers by default.

In my humble opinion, there's an underlying browser problem that causes it to sometimes refetch images when you're using a CSS custom variable and it repaints the element. In our case this occurred only when transitioning the element. The Cache-Control header taps into more low-level browser functionality related to resource caching.

like image 163
doublemarked Avatar answered Sep 18 '22 19:09

doublemarked