DEV Community

Antonio Piras
Antonio Piras

Posted on • Originally published at antopiras.dev on

2 1

Do not use the CSS background shorthand property in React

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 💪🏻

Top comments (2)

Collapse
 
tapesh02 profile image
Tapesh Patel

Thank you for sharing this.

Collapse
 
saidtorres3 profile image
SaidTorres3

Thank you!

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay