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'
}}
/>
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'
}}
/>
That's all! I hope this is useful to you ๐ช๐ป
Top comments (2)
Thank you for sharing this.
Thank you!