Webpack seems to be failing to apply certain styles correctly

Currently, I am in the process of learning how to bundle modules together using webpack. However, I have encountered a roadblock along the way. Within my src folder, there is a CSS file named style.css, a JS file named home.js which contains a function, and another JS file named index.js which imports both before appending them to my webpage.

In style.css, I have added a background image to the body that loads successfully. But oddly enough, the styling applied to a specific element (the 'hi' div) does not seem to take effect. Despite the fact that the element's class does appear when inspecting it on the page.

I can't seem to figure out why this isn't working - what am I missing?

Below are all three files for reference:

//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;
} 

Answer №1

The reason for this issue is that your component loads before the style.css file.

Answer №2

Take a look at the article below, it should help resolve the issue

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

document.head.appendChild(customStyle);

Check out the link below for some examples

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

Answer №3

// It would be great if you could use this and also have the ability to provide dynamic CSS on the fly

var element = document.getElementById("element");

const dynamicValue = 10; 
const darkMode = true;

const styles = `
    background-color:${darkMode ? '#000' : '#fff'};
    color:${darkMode ? '#fff' : '#000'};
    width:${innerWidth - 100}px;
    height:${innerHeight - 100}px;
    display:inline-block;
    border-radius:${dynamicValue}px;
`

element.setAttribute("style", styles)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Identifying CMYK Images Through Javascript Feature Detection

Many are aware that IE8 does not support CMYK JPG images, as it fails to render them at all. This post discusses the issue further: , among others. My inquiry is as follows: Is there a method to detect from JavaScript, akin to Modernizr, whether a browse ...

Learn the process of extracting various data from a PHP source and saving it in select options through AJAX

One of the features on my website is a select option that allows users to choose a hotel name obtained from a dynamic php script. Once a hotel is selected, another select option displays room types available based on the chosen hotel. However, there seem ...

Adding unique parameters to a rails form

As a newcomer to web development, I am facing the following challenge: I have three models in my application: products class Product < ApplicationRecord has_and_belongs_to_many :steps end steps class Step < ApplicationRecord has_and_belongs_ ...

Having difficulty achieving the desired style with columns and four divs per column as the styling is not coming together as expected

I am currently having trouble displaying these articles vertically (stacked on top of each other) with 4 divs per column in the main section. I am unable to make them the same size or have all of them display the articles stacked one on top of the other. S ...

Replacing text within nested elements

I am facing an issue with replacing certain elements on my webpage. The element in question looks like this: <div id="product-123"> <h3>${Title}</h3> <div> ${Description} </div> <div> ${P ...

What is the process for importing module functions in Svelte when utilizing npm?

I'm having trouble understanding how to properly use imports in Svelte with npm. I have a Svelte component that I can't seem to get working. Uncommenting "//import { Configuration, OpenAIApi } from "openai";" leads to the error message: [!] (plug ...

Creating an HTML table row dynamically in MVC4 Razor using Javascript

When working with a Modal Popup window that appends rows to an HTML table after a successful AJAX post, I am encountering an issue. While the appending functionality works properly, I am struggling to incorporate a field value from the modal as a variable ...

Resetting or removing the style attribute using JavaScript in Internet Explorer 9

I have a simple webpage spinner created using the Prototype JS framework: Within the nav frame: Event.observe( 'doit', 'click', function(){ parent.window.frames.cont.spinner.removeAttribute('style'); }, ...

Tips for determining the memory consumption of a JavaScript code snippet

Both JavaScript code achieves the same task of merging the second array into the first one. I have come across various sources claiming that Option 2 is more memory efficient. Is there a way or a tool available for me to verify and actually see if the mem ...

Is it possible to verify if a function is invoked using Jest, Typescript, and ts-jest in action?

Currently, I'm testing the functionality of this code snippet: src/helpers/CommentHelper.ts: export default class CommentHelper { gitApiObject: GitApi.IGitApi ; constructor(gitApiObject: GitApi.IGitApi) { this.gitApiObject = gi ...

`Using asp net core leads to a Fetch: TypeError issue``

I have been working on an application using asp net core with Razor Pages. I spent a lot of time trying to figure out how to process POST requests (specifically OnPost in razor pages). After reading through the documentation at "https://learn.microsoft.com ...

What could be causing the malfunction of my JavaScript code for a basic on-scroll number counter?

I have been working on a JavaScript function to create a counter effect for numbers when scrolled down. Unfortunately, it doesn't seem to be functioning properly and I am struggling to identify the issue. Here is a snippet of my HTML code: <!DOCTYP ...

Encountering an issue with a Vercel deployment of a Next.js project due to an unexpected token error: 'export'

Every time I attempt to compile the latest version of my Next.js project, it throws a build error with the following log. Interestingly, when I execute npm run dev and view the project on the local port, everything functions perfectly. Have any insights? ...

Include a fresh attribute in the Interface

How can I include a boolean property isPhotoSelected: boolean = false; in an API interface that I cannot modify? The current interface looks like this: export interface LibraryItem { id: string; photoURL: string; thumbnailURL: string; fi ...

Can Vue.js components and traditional Vue instances be utilized concurrently within an application?

Currently, my Laravel application utilizes Vue.js as the frontend JavaScript framework. While I employ components for large scripts, I prefer using a Vue instance in the blade template for smaller scripts. The issue arises with my app.js configuration - f ...

Creating a custom Shape Geometry that is derived from BoxBufferGeometry

Looking to create a ShapeGeometry that can be defined by a list of points representing the shape boundary or faces, along with a corresponding list of textures for each face. While the BoxBufferGeometry class provides a starting point, I am in need of guid ...

When a React component initializes state using props, the state does not automatically update when the component receives new props

I am utilizing Next.js with a component that is skeleton-loaded initially as the website awaits data (using tanstack react query): if (isPending) { return <MyComponent name={"Loading...."} hobbies={[]} /> } return & ...

Expo project encountering issues with nested navigation in React-Native

When configuring the header in my app using React Native Stack Navigation and nesting a Drawer Navigation inside of it, I encountered a strange issue. While everything worked fine in the android emulator, opening the app using Expo resulted in nothing but ...

How to update a deeply nested object using a single function in a React component

I have a specific object that requires altering the Ethereum value, for instance; const [reportData, setReportData] = useState({ nameOrganization: "test5", socialMedia: "test", country: "aa", discord: "test", ...

Responsive div that reacts to scrolling

I am looking for a div that can dynamically change its position as I scroll up or down the page. For example, it could start 30px from the top but then move to 100px as I scroll down further. This div will be located on the right-hand side of my page, clo ...