0

I have a css file that has a background image that moves on hover

    .bg {
        width: 400px;
        height: 240px;
        margin: auto;
        background: url (....) no-repeat center center;
        background-size: 100%;
        / * work with the background-size * /
        transition: background-size 1s ease-in-out;
        position: relative;
        z-index: 1;
        box-shadow: 0 4px 8px 0 rgba (0, 0, 0, 1);
    }
    
    .bg: hover {
        background-size: 120% / * work with the background-size * /
    }
    
    .bg :: before {
        position: absolute;
        content: '';
        width: 100%;
        height: 80px;
        background: rgba (0, 0, 0, .5);
        bottom: 0;
        left: 0;
        z-index: -1;
    }
    

It works great.

The problem is that if I set a nice background image in react it does not respond to me when hover

     <div
         class = "bg"
         style = {{
           background: `url (" ... ") no-repeat center center / 100% 100%`,
         }}
       >

I searched the net and found no answer what can we do?

isherwood
  • 58,414
  • 16
  • 114
  • 157
R-S
  • 151
  • 10

3 Answers3

1
 <div
     class = "bg"
     style = {{
       background: `url (" ... ") no-repeat center center / 100% 100%`,
     }}
   >

on hover just change background size with important!

.bg:hover {
  background-size: 120% !important;
}
murli2308
  • 2,976
  • 4
  • 26
  • 47
0

It is not possible to :hover an inline style-element, as :hover is a pseudo-selector and only works inside the style sheet.

See this post on Stackoverflow. So I think it is more a problem with CSS than react which couldn’t be fixed.

Kai
  • 1
  • 1
  • 1
  • 2
  • It it possible to overwrite it with css !important; I have did in answer – murli2308 Jun 08 '21 at 16:05
  • Great to know – somehow I never had to use this case in particularly. As long you are not using !important everywhere this is a really good method! :) – Kai Jun 09 '21 at 08:16
0

I maid small changes (remove spaces and code improvements) and it works fine and response on hover.

Here is my react component

import "./styles.css";

export default function Example() {

    return (
        <div className="bg"/>
    )
}

and styles.css

.bg {
    margin: auto;
    background: url("https://interactive-examples.mdn.mozilla.net/media/cc0-images/grapefruit-slice-332-332.jpg") center center no-repeat;
    height: 100px;
    width: 100px;
    background-size: 100%;
    transition: background-size 1s ease-in-out;
    position: relative;
    z-index: 1;
    box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 1);
}

.bg:hover {
    background-size: 120%
}

.bg::before {
    position: absolute;
    content: '';
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, .1);
    bottom: 0;
    left: 0;
    z-index: -1;
}
Yana Trifonova
  • 586
  • 7
  • 28