Search code examples
cssreactjsemotion

How to select multiple components at once with Emotion?


I have the following styled elements:

const LogoSide = styled.div``
const NavSide = styled.p``
const Nav = styled.nav`
  position: absolute;
  right: 0;
  top: 0;
  width: 100%;

  ${LogoSide} {
    width: 200px; // <-- How to combine those ?
  };
  ${NavSide} {
    width: 200px; // <-- How to combine those ?
  }
`

And I would like to be able to use the same CSS properties for multiple elements, something like this :

const Nav = styled.nav`
  position: absolute;
  right: 0;
  top: 0;
  width: 100%;

  ${LogoSide} ${NavSide} {
    width: 200px;
  };
`

Is there a way to achieve this ?
I looked at the docs but could not find what i'm looking for.


Solution

  • Just put a comma between the components and it will work. You won't find it in the documentation is works just like in plain CSS when you combine classes. But for correct work you need to use Macro.

    All of Emotion's Babel Macros are available by adding /macro to the end of the import you'd normally use. Docs

    import styled from "@emotion/styled/macro";
    
    const NavSide = styled.p`
      border: 2px solid red;
    `;
    
    const LogoSide = styled.div`
      border: 2px solid red;
    `;
    
    const Nav = styled.nav`
      position: absolute;
      right: 0;
      top: 0;
      width: 100%;
      ${LogoSide}, ${NavSide} {
        width: 200px;
      }
    `;
    

    Edit dazziling-code