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

"Effortlessly load images with lazy loading in Mui's ImageList

Currently, I have integrated MUI into my React application. On a particular page, there is a significant amount of images being loaded. My idea is to implement lazy loading functionality for these images based on the user's scrolling behavior. However ...

Is this an effective and appropriate method for establishing media queries?

<link id ="style" rel="stylesheet" type="text/css" title="other" href="regularStyles.css" /> <link rel="stylesheet" media= "all and (mid-width: 767px) and (max-width:2049px) and (min-height:767px) and (max-height: 1538px)" href="notePads.css" /& ...

Having difficulty in converting JSON objects into key/value pairs in Angular 7

I have a task to convert my JSON data from its current format as shown below: cacheMapDataDto = [{ "cacheName": "cache_nchl_individual_type", "count": 2, "mapObj": { "NCHL_BI_BATCH_VERIFICATION": false, "NCHL_STL_BATCH_VERIFICATIO ...

Inline-block divs styled with CSS3 are causing a white gap to appear at the top of

I have been searching for solutions to my problem, but I can't seem to find one that works. My goal is to create two columns that each take up 50% of the screen width. However, I am facing an issue where there is a gap at the top that I cannot seem t ...

Come hang out in the user voice channel by reacting with your favorite emojis!

I am currently developing a Discord bot, and I want to implement a feature where the bot joins a voice channel if a user reacts to its message. I am using the awaitReactions function which only returns reaction and user data. Is there a way to retrieve th ...

Discover how to use Jest and Enzyme to test for any string as the defaultValue on an input field

As a beginner in the world of testing, I've been exploring the airbnb / jest documentation to troubleshoot an issue with a test. So far, I haven't been able to come up with a solution that actually works. The snapshot contains a defaultValue tha ...

When using react-pdf to render images from a backend url, the images fail to load properly

Trying to use react-pdf to render a PDF, but encountering an issue. The problem arises when attempting to display images from a backend server using a URL – they appear blank in the PDF. Upon further investigation, I discovered that placing a breakpoint ...

Vue-Router functions only on specific routes

While my vue-router correctly routes the URL for all menu buttons, it's not displaying each Vue component properly. You can see a demonstration here. Here is a snippet of my HTML (using Vuefy) <div class="navbar-start"> <a ...

RTK Query may sometimes encounter undefined values when fetching data

I am new to using Redux and facing an issue while trying to display data in a Material UI Select. When I try to show the user's name, it works perfectly, but when I do the same for the partner's data, they appear as undefined. In my server index ...

From HTML to Mat Table: Transforming tables for Angular

I am currently facing a challenge with my HTML table, as it is being populated row by row from local storage using a for loop. I am seeking assistance in converting this into an Angular Material table. Despite trying various suggestions and codes recommend ...

What mistakes am I making in this PHP code as I try to work with the select option?

Currently, I am developing a form that involves selecting values. If the user chooses 'yes', I want to display a text box section. However, the code below is not functioning as expected. <select id="gap" name="gap" onclick="gap_textbox();"> ...

HTML elements generated dynamically do not possess any jQuery properties

I have implemented a draggable list of Div elements using jQuery. Here is the code: <div id="external-events"> <h4>List Of Staffs</h4> <div class="external-event" data-id="1">Name</div> //Draggab ...

Do you require assistance with creating an image slideshow?

My first day working with HTML was a success as I successfully built a navigation bar that looks pretty cool. Take a look at it here. Next on my list is to incorporate a slideshow into my site, possibly using JavaScript or jQuery plugins. I'm aiming ...

Creating the perfect layout with CSS: A step-by-step guide

As I work on refining my layout to achieve the desired look, let me share my initial idea before delving into the issue at hand. Currently, I am attempting to create something similar to this: https://i.stack.imgur.com/rtXwm.png This is how it appears a ...

Utilizing Python and Selenium to Locate an Element Based on Text Within a Span Class

My challenge is locating an element without any ID or distinctive identifiers. The HTML code structure resembles the following: <div class="item_select"> <span class="item_selection_number">A </span> </div> <div class="item_ ...

Effective communication among sibling components in Vue.js

Interaction between parent and child components can be easily achieved using $broadcast and $dispatch However, I'm currently faced with a challenge regarding communication between sibling components. My current approach involves triggering a $dispatc ...

Switch out the content when the button is clicked

Seeking a code snippet to enable clicking a button (Button labeled "Next") for replacing existing code on the page with new code. Current code below should be replaced, starting from the score counter section. Please excuse any messy code as I'm new a ...

Prevent the Swiper slider from autoplaying while a video is being played, and automatically move to the next slide once the video is paused or

<div class="swiper mySwiper"> <div class="swiper-wrapper"> <div class="swiper-slide"> <video-js id="6304418462001" class="overlayVideo" data-account= ...

"Transmitting a message with socket.io upon establishing connection

Currently getting the hang of socket.io and giving it a try. I have a straightforward app where clicking the display button shows an image on the screen in real time. I have a couple of questions. Firstly, my main concern is regarding the synchronization ...

Disabling the outline border on bootstrap select elements

I have integrated this plugin into my project and I am attempting to eliminate the blue border when the select box is focused. I attempted to achieve this by setting the outline to none using the following code: *:focus { outline: 0!important; } Additi ...