I want to use css container query with mui. My code shall set the background to red, if the parent width is below 300px.
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>
);
}
You're example is almost there -- to get the Container Query working, you need to add a container-type
to whichever element you want to act as the container. (The square brackets in your example are not needed.)
With your example:
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>
);
}
I've added a few examples in this sandbox showing more example usage with MUI Grid which produces the following based on the size available to the container.
Large example - Content constrained to 100%:
Smaller example - Content constrained to 300px:
Smallest example - Content constrained to 250px:
Working CodeSandbox: https://codesandbox.io/s/mui-container-queries-gvl4fs
Browser Support: https://caniuse.com/css-container-queries