16

I am using css modules, however a library I use in a component to append tweets with JavaScript adds some elements to my component in the following structure:

<div class='user'></div>
<div class='tweet'></div>

I want to now style these elements in my css module for the component, as follows:

MyComponent.css

.user {
 /* styles */
}

.tweet {
 /* styles */
}

However of course now my .user class changes to .MyComponent__user___HZWfM due to the hash naming in the webpack loader.

How can I set a global style in my css module?

3 Answers 3

36

According to the css modules docs, :global switches to the global scope for the current selector. e.g. :global(.example-classname)

So this should work:

:global(.tweet) {
    text-align: left;
}
:global(.user) {
    text-align: left;
}

Or define a global block

:global {
    .tweet {
        text-align: left;
    }
    .user {
        text-align: left;
    }   
}
Sign up to request clarification or add additional context in comments.

1 Comment

It's better to probably combine the css if they are intended to be the same with something like :global(.tweet), :global(.user) { text-align: left }
3

Can use module class with static class with this way.

myStyle.module.css

.moduleClass_g1m59k:global(.StaticClass) {
    background-color: orange;
}

Output will generate like this

.moduleClass_g1m59k.StaticClass {
    background-color: orange;
}

Comments

-1

Many people have struggled with this and there doesn't seem to be any one agreed upon solution. The one I have settled with involves some tweaking of your bundler and specifically addresses the need to import libraries as-is without having to wrap them or edit them manually.

In my webpack config I have set it to scan all files ending css except those within the 'node_modules' and 'src/static' folders. I import my libraries from here and they dont suffer the classname transforms so I am free to use regular classnames for global css and the className={styles.element} convention as usual for modular css (which will compile down to .component_element__1a2b3 or something similar).

Here is an example of a working production webpack config with this solution: http://pastebin.com/w56FeDQA

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.