Search code examples
reactjsmaterial-ui

Make two overlapping Containers with MUI


I am using Material UI (v5) and React, and want to find the best/most elegant way to make two Container (or potential Box or any other container-style element) components overlap. So there's one parent with two child containers, which each have some kind of media element in it (not just an image, so this cannot be done with a simple background-image).

<Container>  {/* Parent container */}

  {/* These two children should overlap. 
      Transparency and z-index is already handled in the media items */}

    {/* Child #1 */}
  <Container>
    <SomeMediaItem1/>
  </Container>

    {/* Child #2 */}
  <Container>
    <SomeMediaItem2/>
  </Container>
  
</Container>

I know this can of course be done in more traditional HTML and CSS, but I would like to know the "proper" MUI way to accomplish this.


Solution

  • You can position the Container with the MUI sx prop :

        <Container sx={{ position: "relative" }}>
          <Container sx={{ position: "absolute", top: "40px" }}>
           <SomeMediaItem1 />
          </Container>
          <Container sx={{ position: "absolute", top: "60px" }}>
            <SomeMediaItem2 />
          </Container>
        </Container>
    

    Here it is in codesandbox