cssreactjsvitecss-modules

Vite React + Bootstrap: CSS rule not applying only to img element


I'm using Vite (React, Bootstrap) to create a React app. I created a component with a specific CSS file imported. The CSS file is being read, as html {color: red} is being applied (and overriden, but img.someclass or div.otherclass won't show anywhere in the DOM, not even overriden.

This is the component.

import "./GameboyBackground.module.css"
import gameboyImage from "/music-games/assets/gameboy/blue.png"

function GameboyBackground() {
  return (
    <>  
    <div>
        <img
          src={gameboyImage}
          alt="gameboy"
          className="gameboy-bg"
        />
      </div>
    </>
  );
}

export default GameboyBackground;

The CSS file looks like this. Again: html element is affected, img is not even overriden.

img.gameboy-bg {
  width: 100vw;
  height: 100vh;
  object-fit: contain;
}


html {
  color: blue;
}

If I try to apply styles inline, the app won't even render, only an empty root div.

<img
  src={gameboyImage}
  alt="gameboy"
  className="gameboy-bg"
  style="width: 100px;"
/>
// App "crashes"

Solution

  • See the Vite documentation for CSS Modules

    Any CSS file ending with .module.css is considered a CSS modules file. Importing such a file will return the corresponding module object

    This creates unique selectors for your styles that you'll need to import in order to use. For example

    // import the class names from your CSS module
    import classes from "./GameboyBackground.module.css";
    
    // ...
    
    return (
      <img
        src={gameboyImage}
        alt="gameboy"
        className={classes['gameboy-bg']}
      />
    )
    

    The actual class name will be something like _gameboy-bg_<hash>