如何在mui中使用css容器查询?

whhtz7ly  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(102)

我想用css容器查询mui。我的代码应该设置为红色的背景,如果父宽度低于300px。
sandbox

const Item = styled("div")(({ theme }) => ({
  border: "solid 1px",
  padding: 100,
  ["@container (max-width: 300px)"]: {
    background: "red",
  },
}));

export default function BasicGrid() {
  return (
    <div>
          <Item>I turn red for width smaller 300 </Item>
    </div>
  );
}
cgvd09ve

cgvd09ve1#

您的示例就快完成了--要让Container Query工作,您需要将container-type添加到您希望充当容器的任何元素。* (您的示例中不需要方括号。)*
以你为例:

const Item = styled("div")(({ theme }) => ({
  border: "solid 1px",
  padding: 100,
  "@container (min-width: 300px)": { // Corrected your query to min-width and removed brackets
    background: "red",
  },
}));

export default function BasicGrid() {
  return (
    {/* Adds containerType to the "container" element */}
    <div style={{ containerType: "inline-size" }}>
          <Item>I turn red for width smaller 300 </Item>
    </div>
  );
}

我在这个沙箱中添加了一些示例,展示了MUI Grid的更多示例用法,它根据容器的可用大小生成以下内容。

大示例-内容限制为100%:

较小的示例-内容限制为300 px:

最小示例-内容限制为250 px:

工作代码沙箱:https://codesandbox.io/s/mui-container-queries-gvl4fs
浏览器支持:https://caniuse.com/css-container-queries

相关问题