I’m trying to set a background image with the CSS properties but with import/export using webpack. I had issues with the CSS rules not applying, and showing crossed out on the development console but I wasn’t sure why or how to fix it.
body {
margin: 0;
max-height: 100vh;
background-size: cover;
background-repeat: no-repeat;
}
The HTML Code is
<html>
<head>
<meta charset="utf-8" />
<title>Asset Management</title>
<script src="bundle.js" defer></script>
</head>
<body>
<div id="content"></div>
</body>
</html>
The exported JS is:
import Background from './background.png';
export const setBackGroundImage = () => {
let body = document.querySelector('body');
body.style.background = `url(${Background})`;
};
The imported JS is:
import './style.css';
import { setBackGroundImage } from './initial-page-load';
setBackGroundImage();
I know this setup is completely unnecessary but it was for TOP, course steps to get used to webpack.
When I load the index.html in the dist/, it shows https://i.imgur.com/38ljGad.png and the CSS file rules being crossed out and overwritten with https://i.imgur.com/aAz1GF7.png which makes the image repeat.
I’m not sure why this is happening and would appreciate any help. I’ve tried setting the image directly on CSS as a background-image, which works, but wanted to practice webpack and was stuck on what I’m missing here.
Thanks!
2
Answers
Does updating your
setBackgroundImage()
function fromto this
instead do what you want? I tested with what you provided, and this seems to fix the issue for me.
The CSS
background
property shorthand contains default values for the other background properties that overwrite your CSS selector due to less specificity than inline on the element (which your javascript is responsible for). If you instead only changebackground-image
which is responsible for the background image, then you will avoid this conflict.Here’s a simple example to illustrate:
As you can see, the element with
background
set does not inherit the background-repeat` value. If you expand the background property (usually there’s a small arrow next to shorthand properties) in your inspector you should be able to see the value has been changed.