skip to Main Content

I don’t know why does my hero section file is inheriting the properties of navbar CSS file. I know that the index.css file passes the properties to entire app, but I don’t use that file instead I make different CSS file for different components. My major problem was with img tag where I gave different style to hero.css file and navbar.css file but unfortunately hero.css file is using the properties of img tag of navbar.css. Thus anybody know how to resolve this issue?

This is just to understand the problem rather this can be resolved by giving another name but I want to know why is it inheriting the properties of other CSS file.

2

Answers


  1. In react, if you have a style of the same selector like ‘img’, even in a different file, both sets of rules will apply to all matching elements in the document.

    Instead, you can separate the style with css module:

    // In your component file
    import styles from './Hero.module.css';
    
    // And in your JSX
    <div className={styles.heroImage}></div>
    
    Login or Signup to reply.
  2. in react, there is only one HTML file, that’s why all css and your react components worked together.
    If you wanna unique css files you can use css modules you can find more information here: 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 don’t wanna use css-modules, you can use styled components here is example for

    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>
      );
    };
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search