skip to Main Content

I’m learning to bundle modules together with webpack and have run into a problem. In my src folder I’ve made a CSS file (style.css), a JS file (home.js) that holds a function and one more JS file (index.js) that I import them both into before appending to my page.

I’ve added a background image to the body in style.css which loads just fine, however the styling I’ve applied to one element (the ‘hi’ div) does not seem to be applied. The elements class does show up when inspecting the element on the page.

Why does this not work – what am I not seeing?

All three files are pasted here:

//index.js:

console.log('hello world');
import square from './home.js';
import './style.css';
const content = document.getElementById('content');

content.appendChild(square());

//home.js:

export default function square() {
    const hi = document.createElement('div');
    hi.classList.add('black');
    hi.textContent = 'boo';

    return hi
};

//style.css:

body {
    margin: 0;
    padding: 0;
    height: 100vh;
    width: 100wv;
    background-image: url('food.jpg');
    background-size: cover;
};

.black {
    background-color: black;
    color: white;
    border: 1px solid;
    padding: 10px;
  } 

2

Answers


  1. It is because your component loads before than your style.css.

    Login or Signup to reply.
  2. You can see the below article hope this resolve the issue

        const style = document.createElement('style');
        style.innerHTML = `
              .note {
                color:"#000";
              }
            `;
    
    document.head.appendChild(style);
    

    the below link have few examples

    https://www.javascripttutorial.netenter code here/dom/css/add-styles-to-an-element/#:~:text=First%2C%20select%20the%20element%20by,properties%20of%20the%20style%20object.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search