Responsive Grid with Card component using React Material UI

Struggling to devise a responsive grid layout with same height cards featuring images in a React and Material-UI setup.

After hours of tinkering, the "flex" part is proving to be quite puzzling. Seeking guidance.

The code snippet in question:

const useStyles = makeStyles((theme: Theme) =>
    createStyles({
        cardGrid: {
            flexGrow: 1,
            paddingTop: 16,
        },
        card: {
            flex: 1,
            height: '100%',
            backgroundColor: 'red',
        },
        cardActionArea: {
            flex: 1,
            height: '100%',
            backgroundColor: 'green',
        },
        cardMedia: {
            height: '0',
            paddingTop: '56.25%', // 16:9
        },
        cardContent: {
            flex: 1,
            backgroundColor: blue[600],
        },
        cardContentTitle: {
            flex: 1,
            backgroundColor: blue[400],
        },
        cardContentRating: {
            backgroundColor: blue[300],
        },
        cardContentDistance: {
            backgroundColor: blue[200],
        }
    }),
);

// ...

<Container className={classes.cardGrid} maxWidth="xl">
    <Grid
        container
        direction="row"
        justify="space-evenly"
        alignItems="stretch"
        spacing={2}
    >
        {
            dataList.map(data => (
                <Grid item
                      key={`GridItem-${data.id}`} xs={12} sm={6} md={4} lg={2} xl={1}
                >
                    <Card className={classes.card}
                          onClick={handleCardClick}
                          key={`OverviewItem-${data.id}`}
                    >
                        <CardActionArea className={classes.cardActionArea}>
                            {
                                data.previewURL &&
                                <CardMedia
                                    className={classes.cardMedia}
                                    image={data.previewURL}
                                    title={data.title}
                                />
                            }
                            <CardContent className={classes.cardContent}>
                                <Typography gutterBottom variant="h5" className={classes.cardContentTitle}>
                                    {data.title}
                                </Typography>
                                <Typography className={classes.cardContentRating}>
                                    Some text
                                </Typography>
                                <Typography className={classes.cardContentDistance}>
                                    Some other text
                                </Typography>
                            </CardContent>
                        </CardActionArea>
                    </Card>
                </Grid>
            ))
        }
    </Grid>
</Container>

My goal:

  • Top placement for image on each card
  • "Some text" and "Some other text" should be at the bottom

It feels like repetitive use of "flex:1" and "height:'100%'" down the tree is causing issues which can be seen in the screenshot below:

https://i.sstatic.net/xcJbw.png

Here's how it looks with the given code snippet above:

https://i.sstatic.net/J8yfT.png

How can I make the child elements within a Grid Item expand to maximum height while aligning them as needed?

For instance, ensuring that the entire card occupies the Grid Item area and the title section beneath the image expands to push the image to the top and move "Some text" and "Some other text" to the bottom.

All suggestions are welcome!

I managed to realize my intended layout without using Cards and images. But increasing nesting depth seems to disrupt everything, and I'm unsure why.

Here's the simplified snippet and its visual output:

<Container className={classes.cardGrid} maxWidth="xl">
    <Grid
        container
        direction="row"
        justify="space-evenly"
        alignItems="stretch"
        spacing={2}
    >
        {
            toiletOverviews.map(data => (
                <Grid item
                      key={`GridItem-${data.id}`} xs={12} sm={6} md={4} lg={2} xl={1}
                >
                    <Box
                        display="flex"
                        flexDirection="column"
                        style={{height: '100%', backgroundColor: 'purple'}}
                    >
                        <Typography
                            variant="h5"
                            style={{flex:1, backgroundColor: blue[800]}}
                        >
                            {data.title}
                        </Typography>
                        <Typography
                            style={{backgroundColor: blue[600]}}
                        >
                            Some text
                        </Typography>
                        <Typography
                            style={{backgroundColor: blue[400]}}
                        >
                            Some other text
                        </Typography>
                    </Box>
                </Grid>
            ))
        }
    </Grid>
</Container>

https://i.sstatic.net/5NTCn.png

Answer №1

After some troubleshooting, I managed to discover the key piece of information that was missing: display:"flex" only affects the current element and its direct descendants. It does not apply to the children of those descendants.

To resolve this issue, I made sure to correctly implement it on all the necessary elements. One side effect was that the image was no longer visible because it had a width/height of zero. The solution was to include width:"100%" in the styling for the CardMedia component.

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

The distance separating the top navigation bar from the sub-navigation menu

I have designed a navigation menu with a subnavigation section, view it on JSFiddle with subnavigation. My challenge is to create a 1px solid white separation between the top navigation (with yellow background) and the subnavigation (with red-colored backg ...

Techniques for breaking down large CSS files into modules and combining multiple smaller CSS files

My website's CSS file is currently massive, containing site-wide selectors in a file named Mondo.css. While this setup has been effective for ensuring users only need to download the file once, I've recently developed a widget that requires its o ...

Creating a Google Inbox-style drawer using Material-UI: A step-by-step guide

I am currently developing an application using Meteor, React, and Material-UI. A custom left navigation component based on Drawer has been implemented. class LeftNav extends Component { constructor(props){ super(props); } render() { ...

Using attribute value for CSS background-image styling is a handy technique to

In my current situation, the design calls for the use of two different images as background images - one for desktop and another for mobile. These images are uploaded through a CMS, allowing me to retrieve the URLs for both using PHP. Is there a way to pa ...

Is it possible to have a full-width thumbnail navigator in a full-width slider container with Jssor Slider?

I apologize if this topic has already been discussed, In a responsive full-width slider container, I am utilizing thumbnail navigator 03 with the scaling option disabled. Is it feasible to have a fixed-height, but fully (100%) width thumbnail navigator t ...

The system encountered an issue trying to access property 'prepareStyles' of an undefined attribute

When I click the button, I am trying to trigger a dialog box to open. However, the dialog is not opening and an error message is displayed: Uncaught TypeError: Cannot read property 'prepareStyles' of undefined. Below is the code for my Compo ...

Can the MUI card variant be altered when hovered over?

<Card variant="outline"> Card 1</Card> I am looking to switch the outline variant of the card to elevation ...

Tips for Including a Parallax Image Within a Parallax Section

Currently, I am working on implementing a parallax effect that involves having one image nested inside another, both of which will move at different speeds. My progress has been somewhat successful, however, the effect seems to only work on screens narrowe ...

HTML Element Split in Two by a Line in the Middle

Greetings to all, after observing for a while I have decided to make my first post here (and just to clarify, I am an electrical engineer, not a programmer). I am in search of creating a unique element in HTML where I can detect clicks on both its upper a ...

Unable to set width for td element in media query is not functioning as expected

Is there a way to adjust the width of td elements for smaller screens within an email template? I have tried setting the style as important, but it doesn't seem to be working. CSS .alignmentColumn { width: 25% !important; //for desktop @med ...

I'm puzzled as to why my Contact Form is failing to send out emails

Looking to create an email send function in a pop-up on my website that can be accessed via the following link: The issue I'm facing is that while it redirects perfectly to the thank you message, the PHP implementation does not seem to work after the ...

Adjust the material UI select width according to the size of the label

Here's my issue with a select component: <FormControl className={classes.formControl}> <InputLabel htmlFor="age-native-simple">{this.props.label}</InputLabel> <Select native value={this.state.valu ...

Mastering the Art of Stacking with FontAwesome

I am working on stacking the Soundcloud icon manually to display it within a square similar to fa-facebook-square. However, my Soundcloud icon is appearing under the square. This is the code I have so far: <div class="row"> <ul style="list-s ...

Exploring the beauty of background color curves in React Native

Struggling to figure out how to create a curved background color on the top (header part) of my design. Check it out I'm looking to achieve this curved design for my header part Here is the code snippet I have so far: <View style={{backgroundColo ...

My HTML Won't Recognize the CSS File

Despite trying various paths and browsers, I am unable to link my CSS file to my HTML file. When inspecting the page elements and checking under resources, the CSS file does not appear. Here is a snippet of my HTML: <html> <head> <meta ...

php failure to execute included file

Hey there! I'm currently facing an issue with including a file that contains all of my 'head' information. My goal is to simplify and streamline my page by breaking it down. In my index.php file, here's what I did: <?php include & ...

What is the title of this particular CSS method?

I've been implementing a unique approach for more than a year now, and I have yet to come across similar practices elsewhere. Essentially, I am structuring display "states" or "modes" by utilizing CSS classes. Despite searching for terms like "css mod ...

In React js, automatically insert a new row into a table once the Dialog window has

I am currently exploring Reactjs and using Material UI Dialog to implement a dialog box for users to input information and interact with a POST API. After the process is completed, the dialog closes but I would like to dynamically display the added informa ...

Stepper that is vertical combined with table information

I am currently facing a unique challenge with a component I'm trying to create. It's a combination of a vertical Stepper and a Datagrid. My goal is to group specific table sections within the content of a vertical Stepper, purely for data visual ...

What could be causing the TailWind CSS Toggle to malfunction on my local server?

While working on designing a sidebar for a ToDo page using Tailwind CSS, I encountered an issue with implementing a toggle button for switching between dark mode and light mode. In order to achieve this functionality, I borrowed the toggling code snippet f ...