Tips for utilizing CSS container queries in conjunction with the Material-UI framework

I'm looking to implement CSS container queries with MUI. In my code, I want to change the background color to red if the parent width is less than 300px.

Check out the sandbox

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

export default function BasicGrid() {
  return (
    <div>
          <StyledItem>I will turn red when the width is under 300 pixels</StyledItem>
    </div>
  );
}

Answer №1

Your example is almost there -- to make the Container Query work, you just need to include a container-type on the element you want to use as the container. (The square brackets in your example are unnecessary.)

In your code snippet:

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 than 300</Item>
    </div>
  );
}

I have provided additional examples in this sandbox that demonstrate using MUI's Grid, adjusting content based on the available size of the container.

Large example - Content constrained to 100%:

https://i.stack.imgur.com/VJDqc.png

Smaller example - Content constrained to 300px:

https://i.stack.imgur.com/HiCI2.png

Smallest example - Content constrained to 250px:

https://i.stack.imgur.com/VV649.png

Working CodeSandbox: https://codesandbox.io/s/mui-container-queries-gvl4fs
Browser Support: https://caniuse.com/css-container-queries

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the most effective way to stop zooming when focusing on form fields on iOS or similar devices when using font sizes of 16px or lower?

It appears that many proposed solutions involve changing the text to 16px or using JavaScript to determine if the phone is an iPhone. However, altering the style may not be the most practical solution and checking for specific devices like iPhones could ...

How can I create a custom elevation for a Vuetify v-menu?

I'm currently working with vuetify and v-menu as outlined in the official documentation here https://vuetifyjs.com/en/components/menus/ I'm struggling to figure out how to apply elevation only on the bottom left and right corners. When I add a ...

Guide on programmatically importing excel/CSV data into MongoDB collection/documents using MERN stack

I have a spreadsheet containing employee information. My objective is to save this data from the Excel file into a MongoDB database, specifically in the employee collection (each row from the spreadsheet as a document in MongoDB). This process is being car ...

Invalid prop type: The Grid component requires the justify prop to be used on a container

I encountered an issue while working with Material-UI in a React project <Grid container justify="center"> <Box className={classes.box}> <Grid item className={classes.item1}> <Typography variant="h5" c ...

Bootstrap 3's Clear:Left Media Query Feature

Bootstrap is being used, and there is a div with col-xs-12, col-sm-6, col-md-4 classes. Task : To add a clear on every 1 item for col-xs-12, add a clear on every 2 items for col-sm-6, and clear on every 3rd item for col-md-4. The current code only s ...

Invoke the do_action function with JavaScript/jQuery

After successfully logging in through Facebook, my AJAX function sends information to the userpro_ajax_url. In order to run a do_action function within the success block, I am trying the following: <?php ob_start(); do_action('userpro_social_l ...

Having difficulty rearranging choices within an optgroup

This is a dropdown <select id="officer-id" placeholder="Choose an officer"> <option selected="selected" >----</option> <optgroup id="pt1" label="To be reviewed"> <option value=&ap ...

Can you explain the distinction between the "DOMContent event" and the "load event"?

Within Chrome's Developer tool, there is a blue vertical line marked "DOMContent event fired", as well as a red line labeled "load event fired". Is it safe to assume that the "DOMContent event fired" signifies the initiation of inline JavaScript execu ...

What is the process for updating the internal TypeScript version in VS Code?

When using VS Code, I noticed it comes with its own TypeScript version: Is there a way to update this? The current version is 4.9.3. ...

What is causing the element to disappear in this basic Angular Material Sidenav component when using css border-radius? Check out the demo to see the issue in action

I have a question regarding the Angular Material Sidenav component. I noticed that in the code below, when I increase the border-radius property to a certain value, the element seems to disappear. <mat-drawer-container class="example-container" ...

Exploring the features of NextJS version 13 with the benefits

Starting from the 13th step, SSR is utilized by default and in order to opt for client side rendering you must specify it at the top like so: 'use client' Currently, my setup involves TypeScript and styled-component integration. Take a look at ...

Is there a way to set the background of a HTML5 page as an image with a clickable link?

Lately, I've been working on a webpage dedicated to educating people about Mars. I wanted to spice things up by using an image as the background for my HTML5 page instead of the usual plain white color. However, just inserting a .jpg link didn't ...

Conquering cross-origin resource sharing (CORS) using XMLHttpRequest without relying on JSONP

Appreciate your time in reading this inquiry! For the past few days, I've been grappling with an AJAX request issue. Despite scouring through numerous answers on Stack Overflow, I'm still unable to find a resolution. Any assistance would be grea ...

Discovering the amount of attributes possessed by an element with jQuery

If I have an xml element like this: <fruit color="blue" taste="sweet" shape="round"></fruit> Without using jQuery, I could use the following code: fruit.attributes.length How can I achieve the same result with jQuery? ...

I'm having trouble getting CSS to apply to my HTML file. Any idea why?

I conducted tests in both Chrome and Firefox, ruling out any browser-related issues. My CSS has been validated and is error-free. However, when I validate my HTML code, an error message pops up stating "Bad value “stylesheet” for attribute rel on eleme ...

Find any consecutive lowercase or uppercase letter and include one more

I have a task in Javascript that I need help with. The goal is to insert a special character between a lowercase and uppercase letter when they are matched together. For example: myHouse => my_House aRandomString => a_Random_String And so on... T ...

What is the AngularJS equivalent of prevAll() and nextAll() functions in jQuery?

Currently, I am working on a project that involves AngularJS and I'm having trouble finding an example that fits my needs... With AngularJS, I know how to apply a class when an element is clicked, but how can I add a class to all previous items and r ...

What is the best way to show real-time values using chart js?

Just recently, I've delved into the world of web development and am eager to learn how to integrate chart js for real-time value display. Could anyone offer advice or guide me through the process? var data = []; var temp = []; async f ...

Is requesting transclusion in an Angular directive necessary?

An issue has cropped up below and I'm struggling to figure out the reason behind it. Any suggestions? html, <button ng-click="loadForm()">Load Directive Form</button> <div data-my-form></div> angular, app.directive(&apos ...

Implementing clickable URLs in ag-Grid using React

Currently experimenting with ag-grid and attempting to create a table where users can click on a column value to be directed to a page with more details about that specific entry. Is there a way to make a cell value clickable in ag-grid? I've been t ...