mui / pigment-css

Pigment CSS is a zero-runtime CSS-in-JS library that extracts the colocated styles to their own CSS files at build time.
MIT License
820 stars 39 forks source link

Generate @media styles dynamically #322

Closed acomanescu closed 1 week ago

acomanescu commented 1 week ago

Summary

I have a case where I want to define my breakpoints in a JS file since CSS variables cannot be used in @media selectors and I am not able to generate the styles dynamically, even if that can be done at build time and not at runtime.

Examples

const breakpoints = {
  xs: 0,
  sm: 640,
  md: 768,
  lg: 1024,
  xl: 1280,
} as const;

const lessThan = (breakpoint: keyof typeof breakpoints) => {
  return `@media (max-width: ${breakpoints[breakpoint] - 1}px)`;
};

const greaterThan = (breakpoint: keyof typeof breakpoints) => {
  return `@media (min-width: ${breakpoints[breakpoint]}px)`;
};

export default function Layout({ children }: LayoutProps): React.JSX.Element {
  return (
    <div
      className={css({
        display: "grid",
        [greaterThan("md")]: {
          gridTemplateColumns: "var(--sidebar-width) 1fr",
        },
     } as React.CSSProperties)}
   >

Apparently this results in an error: Error: greaterThan is not defined.

I wasn't able to find any resource about this. Is it possible?

Motivation

This allows us to have a global way to define the media breakpoints.

Search keywords: styles, media

brijeshb42 commented 1 week ago

Have you considered adding these methods in the theme itself ? Like

const pigmentConfig = {
  theme: {
    // ... rest of the theme,
    lessThan: (breakpoint: keyof typeof breakpoints) => {
      return `@media (max-width: ${breakpoints[breakpoint] - 1}px)`;
    },
    greaterThan: (breakpoint: keyof typeof breakpoints) => {
      return `@media (min-width: ${breakpoints[breakpoint]}px)`;
  },
}

Then in your source, you can do

css(({ theme }) => ({
        display: "grid",
        [theme.greaterThan("md")]: {
          gridTemplateColumns: "var(--sidebar-width) 1fr",
        },
     } as React.CSSProperties))
acomanescu commented 1 week ago

Hi @brijeshb42 . Thank you, that's exactly what I was looking for! Works great.

github-actions[bot] commented 1 week ago

This issue has been closed. If you have a similar problem but not exactly the same, please open a new issue. Now, if you have additional information related to this issue or things that could help future readers, feel free to leave a comment.

[!NOTE] @acomanescu How did we do? Your experience with our support team matters to us. If you have a moment, please share your thoughts in this short Support Satisfaction survey.