reactjsemotion

How can I use media query with emotion/styled/macro?


I cannot find any code that using styled macro with media query and don't understand why It's so rare to find code using emotion/styled/macro.

I know it allows css style in object literal

const StyledUl = styled("ul")(
    {
        backgroundColor: "#fff",
        height: "200px",
        width: "100%",
        overflowY: "scroll",
        position: "absolute",
        margin: 0,
        padding: "5px",
        boxShadow: "-1px 15px 34px -21px rgba(0,32,86,0.21)",
        boxSizing: "border-box",
        borderRadius: "8px",
        zIndex: 9999,
    }
)

But how can I use media query? And where can I find documentation about emotion/styled/macro?


Solution

  • Nothing special is required. Just add a @media ... query as a property:

    import styled from "@emotion/styled/macro";
    
    const StyledUl = styled("ul")({
      "@media (max-width: 600px)": {
        backgroundColor: "#000",
        color: "#fff"
      },
      backgroundColor: "#fff",
      height: "200px",
      width: "calc(100% - 40px)",
      overflowY: "scroll",
      position: "absolute",
      margin: 0,
      padding: "5px",
      boxShadow: "-1px 15px 34px -21px rgba(0,32,86,0.21)",
      boxSizing: "border-box",
      borderRadius: "8px",
      zIndex: 9999
    });
    
    export default StyledUl;
    

    Optionally, you can use a template literal to style a styled.HTMLElement:

    import styled from "@emotion/styled/macro";
    
    const StyledUlTemplate = styled.ul`
      @media (max-width: 600px) {
        background-color: #000;
        color: #fff;
      }
    
      background-color: #fff;
      height: 200px;
      width: calc(100% - 40px);
      overflow-y: scroll;
      position: absolute;
      top: 60%;
      margin: 0;
      padding: 5px;
      box-shadow: -1px 15px 34px -21px rgba(0, 32, 86, 0.21);
      box-sizing: border-box;
      border-radius: 8px;
      z-index: 9999;
    `;
    
    export default StyledUlTemplate;
    

    Demo (drag the middle bar left/right to resize the Browser tab to trigger the style changes):

    Edit Emotion Media Property in Object