DEV Community

loading...

Do not use the CSS background shorthand property in React

antopiras89 profile image Antonio Piras Originally published at antopiras.dev on ・1 min read

The problem

I recently came across this bug at work and it took me a minute to figure it out. What I had was something like this:

<div 
  className="image-container" 
  style={{ 
    position: 'absolute', 
    top: `${top}%`, 
    left: `${left}%`, 
    width: `${width}%`, 
    height: `${height}%`, 
    background: `transparent url(${image_url}) no-repeat 
    center center`, backgroundSize: 'contain'
  }}
/>
Enter fullscreen mode Exit fullscreen mode

Everything seems okay, right? Well, in theory. But as soon as the application started, I noticed that the backgroundSize property was not working!

Let’s get googling

After inspecting the output HTML and a bit of googling, I came across this closed issue on React's Github.

Apparently, using the CSS background shorthand property with a backgroundSize prop causes this last property to be cleared if and when the background property is updated.

Fair enough, let’s fix it

A quick and easy fix is to explicitly set every property by expanding the shorthand property:

<div 
  className="image-container" 
  style={{ 
    position: 'absolute', 
    top: `${top}%`, 
    left: `${left}%`, 
    width: `${width}%`, 
    height: `${height}%`, 
    backgroundColor: 'transparent', 
    backgroundImage: `url(${image_url})`, 
    backgroundRepeat: 'no-repeat', 
    backgroundPosition: 'center center', 
    backgroundSize: 'contain' 
  }}
/>
Enter fullscreen mode Exit fullscreen mode

That's all! I hope this is useful to you 💪🏻

Discussion (0)

pic
Editor guide