CSS class selector styles not being applied in React Project

前端 未结 4 2042
鱼传尺愫
鱼传尺愫 2021-01-13 07:52

Working on a React project using Webpack. Adding some styles in style.css and importing into component with import style from \'./style.css\';. Elements without

相关标签:
4条回答
  • 2021-01-13 08:12

    If you're like me and use the style attribute for styling then afterwards move them into proper classes in .css files (and wonder why it doesn't work), remember to remove the JSX string format,

    height: "100px"
    

    is not the same as

    height: 100px
    
    0 讨论(0)
  • 2021-01-13 08:12

    My solution is to rename the css file from:

    style.css
    

    to:

    style.module.css
    
    0 讨论(0)
  • 2021-01-13 08:21

    Your webpack configuration may be changing the class name depending on its settings. (CSS Modules enabled, though your comment about stylesheet intact implies it's not).

    Since you are importing the './style.css' file, try referencing the class name like: style.foo. Ex:

    <div className={ style.foo }>foo div</div>
    

    This article: http://javascriptplayground.com/blog/2016/07/css-modules-webpack-react/ describes the pattern of importing and referencing the class name pretty well.

    0 讨论(0)
  • 2021-01-13 08:27

    While Kyle's answer works, a better solution would be to rename the css file as style.global.css and import it with import './style.global.css' and specify the class name like normal html. this works better for when you want to append different class names at run time

    <div className='foo'>foo div</div>
    
    0 讨论(0)
提交回复
热议问题