5

I'm currently need to integrate common components of a library into multiples websites. The component Library currently have a Global styles. That they inject in the following way:

  <Global
    styles={`
        div {
          padding: 0;
        }
    `}
  />

I want there "Global styles" only available for the components of this library. They are only on a part of the page.

So I've try this:

const Styles = styled.div`
        div {
          padding: 0;
        }
`;

const Page = () => (
    <Styles>
        <SomeComponentsOfTheLibrary />
    </Styles>
);

But it seems that everything in Styles has the priority. Then if the component has padding: 10px; it will take padding: 0; of Styles

Here is the issue reproduced:

I know it's a css issue but I want to solve it with emotion

I've already saw:

Julien Kode
  • 5,010
  • 21
  • 36
  • I know it relys on the order of creation https://stackoverflow.com/questions/3066356/multiple-css-classes-properties-overlapping-based-on-the-order-defined – Julien Kode Mar 06 '20 at 15:43

1 Answers1

3

How to move global styles into a scope for emotion ?

@Andarist found a solution for that by creating a stylis plugin for extra scope

Example

Create a cache with stylis plugin for extra scope

const STRONG_ID = 'very-strong-id';
const cache = createCache({
  stylisPlugins: [createExtraScopePlugin(`#${STRONG_ID}`)],
});

Use your global styles in the cache provider

     <CacheProvider value={cache}>
        <Global
          styles={css`
            div {
              background-color: red;
            }
          `}
        />
        <div id={STRONG_ID}>
          <div>I must be red (global style scoped to the parent div)</div>
          <Container>
            I must be blue (local style defined on this div)
          </Container>
        </div>
      </CacheProvider>

Then your global styles will be scope by very-strong-id

You can find the example here

Hope it will help someone in the future

Julien Kode
  • 5,010
  • 21
  • 36