【问题标题】:MUI JSS combine media queries without repetitionMUI JSS 组合媒体查询而不重复
【发布时间】:2021-05-19 00:30:30
【问题描述】:

我有一组 CSS 样式需要应用于多个媒体查询规则。有没有办法做到这一点而不重复?目前,这样的事情似乎是唯一的 jank 方式:

[theme.breakpoints.up('xl')]: {
  color: 'red',
  backgroundColor: 'green',
  border: '1px solid blue',
  fontSize: 17,
  marginTop: 3,
  padding: 7,
  display: 'flex',
  flexDirecton: 'column',
},
[theme.breakpoints.only('md')]: {
  color: 'red',
  backgroundColor: 'green',
  border: '1px solid blue',
  fontSize: 17,
  marginTop: 3,
  padding: 7,
  display: 'flex',
  flexDirecton: 'column',
},
[theme.breakpoints.down('xs')]: {
  color: 'red',
  backgroundColor: 'green',
  border: '1px solid blue',
  fontSize: 17,
  marginTop: 3,
  padding: 7,
  display: 'flex',
  flexDirecton: 'column',
}

【问题讨论】:

  • @RyanCogswell 提出澄清问题通常很有帮助。但并非每个问题都要求提供功能代码示例。这个问题是(并且一直是)关于避免重复的问题,而 imo 专注于代码示例完全没有抓住重点。

标签: css reactjs material-ui jss


【解决方案1】:

首先要意识到theme.breakpoints 方法并没有什么神奇的功能——它们只是生成媒体查询字符串的便捷方法。

例如,theme.breakpoints.down('xs')(使用默认断点值时)计算结果为 @media (max-width:599.95px)theme.breakpoints.only('md') 计算结果为 @media (min-width:960px) and (max-width:1279.95px)。您可以在createBreakpoints function 中找到 Material-UI 代码。

下一步是了解在 CSS(和 JSS)中实现目标的语法。 Commas 可用于执行多个媒体查询条件的“或”,因此您要为问题中的示例生成的字符串如下:

@media (max-width:599.95px), (min-width:960px) and (max-width:1279.95px), (min-width:1920px)

为避免对断点值进行硬编码,您可以通过将所需的函数调用串在一起(用逗号)并去掉@media 的无关情况来生成上述字符串,因为这应该只在开头出现一次。

这是一个工作示例:

import React from "react";
import Button from "@material-ui/core/Button";
import { makeStyles } from "@material-ui/core/styles";

const useStyles = makeStyles((theme) => ({
  button: {
    color: "white",
    backgroundColor: "purple",
    [`${theme.breakpoints.down("xs")},${theme.breakpoints
      .only("md")
      .replace("@media", "")},${theme.breakpoints
      .up("xl")
      .replace("@media", "")}`]: {
      color: "red",
      backgroundColor: "green",
      border: "1px solid blue",
      fontSize: 17,
      marginTop: 3,
      padding: 7,
      display: "flex",
      flexDirecton: "column"
    }
  }
}));
export default function App() {
  const classes = useStyles();
  return (
    <Button className={classes.button} variant="contained">
      Hello World!
    </Button>
  );
}

相关回答:How can I use CSS @media for responsive with makeStyles on Reactjs Material UI?

【讨论】:

  • 啊!我完全尝试过,但显然做错了。感谢您花时间忍受我。
猜你喜欢
  • 2018-02-01
  • 1970-01-01
  • 2020-04-07
  • 1970-01-01
  • 1970-01-01
  • 2016-04-29
  • 1970-01-01
  • 2020-06-18
  • 2012-11-10
相关资源
最近更新 更多