What causes one CSS file's properties to be inherited by another CSS file in a React application?

I'm puzzled as to why my hero section file seems to be adopting the styling from the navbar CSS file. I do understand that the index.css file sets properties for the entire app, but in my case, I have separate CSS files for different components instead of using that one. A specific issue I've encountered involves the img tag - where I've applied different styles in both hero.css and navbar.css files, yet somehow the hero.css file is picking up the properties defined in the navbar.css file's img tag. Has anyone else experienced this problem, and if so, how did you resolve it?

This question isn't necessarily looking for a quick fix by renaming elements, but rather seeks to gain an understanding of why this cross-styling between CSS files is happening.

Answer №1

If you're using React and have a style with the same selector, such as 'img', even if it's in a different file, both sets of rules will be applied to all matching elements in the document.

One way to avoid this is to separate the styles using css modules:

// Import the styles in your component file
import styles from './Hero.module.css';
// Use the imported styles in your JSX
<div className={styles.heroImage}></div>

Answer №2

When working with React, all CSS and components are contained within a single HTML file for seamless integration. For unique CSS files, consider using CSS modules. More information can be found at: https://create-react-app.dev/docs/adding-a-css-modules-stylesheet/

import React from 'react';
import styles from "./my-styles.module.css";

const MyComponent = () => {
  return (
    <div className={styles.container}>
      <h1 className={styles.redHeader}>Hello World!</h1>
      <h2 className={styles.grayHeader}>This text is gray</h2>
    </div>
  );
};

If you prefer not to use CSS modules, another option is styled components. Here's an example:

import React from 'react';
import styled from 'styled-components';

const Container = styled.div`
  padding: 10px 20px;
  text-align: center;
`;

const RedHeader = styled.h1`
  color: red;
  font-size: 48px;
`;
const GrayHeader = styled.h2`
  color: gray;
  font-size: 32px;
`;

const MyComponent = () => {
  return (
    <Container>
      <RedHeader>Hello World!</RedHeader>
      <GrayHeader>This text is gray</GrayHeader>
    </Container>
  );
};

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

NextJS React - WebpackError: Cannot access 'window' before initialization

I'm delving into the world of React and recently completed the "Getting Started" tutorial for NextJs (link), successfully setting up a new project. However, when attempting to import third-party plugins like current-devices or smooth-scrollbar, I enc ...

Encountered a compiling error when attempting to watch for changes on the ./folder directory using the

An unexpected exception occurred: NullError: method 'length' not found on null File: /usr/local/lib/node_modules/sass/sass.dart.js Line: 8583:23 Function: tF.eA File: /usr/local/lib/node_modules/sass/sass.dart.js Line: 8585:28 Function: tF. ...

When there are numerous websocket connections in Google Chrome, Socket.io can encounter issues and break down

I am encountering an issue where I create 60 client connections to a socket.io server using Google Chrome browser. The server sends screenshots to the clients at specific times, but some of the websocket connections, which are subprotocols of socket.io, ge ...

Restricting data list values in AngularJS

Currently, I am facing a performance issue while trying to display approximately 2000 values retrieved through an API call using DataList in AngularJS. The page becomes extremely slow due to the large number of items being rendered. Is there a way to optim ...

What is causing Safari to block styling for <em> elements in RESET.CSS only?

I am utilizing Eric Meyer's reset.css file, which can be found at this link: Interestingly, my <em> definition in my main stylesheet is working perfectly fine on all browsers except Safari. Somehow, only in Safari, the styling for italics is no ...

`Turn a photo into a circular shape by cropping it`

Even though I know that the solution involves using border-radius: 50%, it doesn't seem to be working for my situation. In my code using React/JSX notation, this is how the icon is displayed: <i style={{ borderRadius: '50%' }} className= ...

Exploring methods to retrieve data from the web3 platform through Node.js

Is there a way to retrieve token information such as name, symbol, and decimals using Nodejs in conjunction with web3js? ...

Tips for effectively logging data retrieved through Ajax requests

When I have content loaded via Ajax with two divs and a list, my goal is to console.log which div I was typing on when clicking on a list item. However, the issue I'm facing is that I always get the first one I clicked until I refresh the page. Altho ...

Enhancing the appearance of a checkbox within a ReactJS setting

I'm having trouble customizing a checkbox in a ReactJS environment for IE11. I've tried various approaches, but nothing seems to work. Can anyone offer any advice? Here is the code snippet: CSS: .squared { input[type=checkbox] { bo ...

Determine the selected option in the dropdown menu upon loading the page and when clicked

I am working on capturing the value of a drop-down list whenever it is changed or when the page loads. The aim is to display different div elements based on the selected option in the report field - either State or Year. Any assistance with this would be ...

Execute asynchronous JavaScript request

When a user types something into the input id=2, an ajax function triggers. Here is the HTML: <input id="2" type="text" onkeyup="posttitulo(this.value)" /> And here is the SCRIPT: function posttitulo(value){ $.post("getdata/posttitulo.php",{p ...

Tips for implementing a dotted text decoration using Material UI <Link>

I am having trouble implementing a dotted underline effect on hover for a Material-UI <Link> component. Despite using the code below, it doesn't seem to work: const useStyles = makeStyles(theme => ({ link: { '&hover': { ...

I'm looking to adjust the position of an image inside a div without affecting the position of the entire div

When creating a horizontal navigation bar with an image, I encountered an issue where the image link did not align with the rest of the links on the navigation bar. I wanted to drop it down by a pixel or two without affecting the position of the other link ...

How can you display '<>' characters in a QLabel and set text accordingly?

In my PySide2 (similar to PyQt5) project, I am facing an issue with setting text in a QLabel that includes characters like '<' and '>'. These characters seem to disappear because they are used for font modifications. I have tried ...

What is the process for initiating printing in a separate window?

Is there a way to modify the code below so that when I click "Print" it opens in a new window instead of redirecting and losing the original receipt? <div class="print_img"> <button onclick="myFunction()"> <div align="justify ...

What do you mean my cookie isn't working?

I'm going crazy over this! There's a cookie that was set from a response header with the sessionid, visible in dev tools on Chrome and Firefox, but document.cookie shows an empty string. This is what the cookie looks like: Name: sessionid Value ...

Issue with JQuery Ajax button functionality

I am brand new to navigating the world of writing ajax and using a restful api...so please bear with me. On the backend, I have a Laravel 5.2 RESTful API that I'm working with, and my current task involves loading a list of categories using Jquery / ...

Updating image URL for grouped objects with Fabric JS

Check out this link :http://jsfiddle.net/mishragaurav31/ang58fcL/#base I created two groups of objects; one consisting of a circle and text, and the other with two images. When I try to change attributes for group 1, it works fine. However, when attempt ...

conceal child component upon hover using styled-components

As mentioned in the title, this code works perfectly fine with styled components that are within the same js file, as long as they are ordered procedurally above. However, when it comes to imported child components, I'm facing some difficulties in get ...

Updating reactive form fields with patched observable data in Angular

Struggling with initializing a reactive form in my component's onInit() method, as well as handling data from a service to update or create entries in a MySQL table. The issue lies in using patchValue to pass the retrieved data into the form: compone ...