What is the best way to display Material UI cards in a horizontal layout?

I'm currently incorporating Material UI into my project,

Within my list of cards, I aim for them to display one after the other horizontally and then continue in the same fashion on the next row. However, they are currently stacking vertically.

I've attempted to apply some custom CSS without success. Could someone please review my code? At this point, there are only two cards present. By utilizing the box, I managed to add some margin to the cards. But how can I achieve the desired layout where they appear side by side?

function Blogs() {
    const [expanded, setExpanded] = React.useState(false);

    const handleExpandClick = () => {
        setExpanded(!expanded);
    };

    return (
        <>

        <Box m={6}>
        <Card sx={{ maxWidth: 345 }}>
          <CardHeader
            title="It’s a cocktail o’clock."
            subheader="May 14, 2021"
          />
          <CardMedia
            component="img"
            height="194"
            image="https://img.freepik.com/free-photo/selection-various-cocktails-table_140725-2909.jpg?w=2000"
            alt="Paella dish"
          />
          <CardContent>
            <Typography variant="body2" color="text.secondary">
            Beat The Heat With Chilled Cocktails At The Best Bars In New York.
            </Typography>
          </CardContent>
          <CardActions disableSpacing>
            <ExpandMore
              expand={expanded}
              onClick={handleExpandClick}
              aria-expanded={expanded}
              aria-label="show more"
            >
              <ExpandMoreIcon />
            </ExpandMore>
          </CardActions>
          <Collapse in={expanded} timeout="auto" unmountOnExit>
            <CardContent>
              <Typography paragraph>To a foodie, summer means one thing and one thing only – DRINKS!</Typography>
              <Typography paragraph>
              Yes people, we know it's hot out there and the only way to quench your thirst is by guzzling down a bunch of ice-cold cocktails
              </Typography>
              <Typography paragraph>
                <h4>1.The Bar Room at The Beekman</h4>
                Visit the beautiful Bar Room in the historic Beekman Hotel for high-key romance that really wows.
                Do try the whiskey sour.One of the best drinks available.
                <h4>2.Dublin House</h4>
                You can never go wrong with Sláinte! Margarita,Pot O'Gold, & Irish Old Fashioned
              <h4>3.Russian Samovar</h4>
              Alpensahne,Amarula Cream Liqueur, Caribou,Feni
              </Typography>
            </CardContent>
          </Collapse>
        </Card>
        </Box>

        <Box m={6}>
        <Card sx={{ maxWidth: 345 }}>
          <CardHeader
            title="Winner Winner Pizza Dinner"
            subheader="May 14, 2021"
          />
          <CardMedia
            component="img"
            height="194"
            image="https://cdn.shopify.com/s/files/1/0624/9853/articles/20220211142645-margherita-9920.jpg?crop=center&height=800&v=1660843558&width=800"
            alt="Pizza dinner"
          />
          <CardContent>
            <Typography variant="body2" color="text.secondary">
            A delectable pizza delight awaits you as the winner!
            </Typography>
          </CardContent>
          <CardActions disableSpacing>
            <ExpandMore
              expand={expanded}
              onClick={handleExpandClick}
              aria-expanded={expanded}
              aria-label="show more"
            >
              <ExpandMoreIcon />
            </ExpandMore>
          </CardActions>
          <Collapse in={expanded} timeout="auto" unmountOnExit>
            <CardContent>
              <Typography paragraph>Indulge in some mouth-watering slices of pizza, knowing that victory tastes oh so good!</Typography>
              <Typography paragraph>
              Treat yourself to the most amazing flavors while savoring every bite of that delicious pizza goodness.
              </Typography>
              <Typography paragraph>
                <h4>1.Margherita Pizza</h4>
                Experience perfection in simplicity with this classic pizza loaded with mozzarella cheese and fresh basil leaves.
                Enjoy each cheesy bite and feel the Italian pizza magic come alive!
              <h4>2.Pepperoni Passion Pizza</h4>
              Succumb to your pepperoni cravings with this meaty marvel topped with spicy pepperonis dancing on melted cheese and harmonizing tomato sauce.
              Give in to the enticing flavors and enjoy every slice of this delightful creation.
              </Typography>
            </CardContent>
          </Collapse>
        </Card>
        </Box>

      </>
    );
}
export default Blogs;

Answer №1

For a responsive layout with horizontal rows, consider using MUI Grid

import { Grid } from "@mui/material"

<Grid container direction="row" justifyContent="center">
   <Grid item xs={4}>
     <Card> ..... </Card>
   </Grid>
   <Grid item xs={4}>
     <Card> ..... </Card>
   </Grid>
   <Grid item xs={4}>
     <Card> ..... </Card>
   </Grid>
</Grid>

In this setup, xs={4} will show 3 Cards in each row because MUI follows a 12-column grid system. Adjust with md, sm, lg, and xl for various screen sizes.

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

Within the materia-ui table, I am facing an issue where clicking the button to expand a row results in all rows expanding. I am seeking a solution to ensure only the selected row expands

When a row is clicked, all rows in the data table expand to show inner data for each row. The issue is that clicking the expand button expands all rows rather than just the selected row. Each time I try to expand one specific row, it ends up expanding mul ...

Trouble with React Material Select Options Failing to Populate

After iterating and producing MenuItems, I am able to see the items when I console.log, but in the UI, the dropdown appears empty. I'm puzzled as to why the Select's are not being populated. Any thoughts on this issue? Below is the supplied code ...

Can you explain the significance of the "table$aria-label" and "input$autocomplete" attributes in the context of Svelte SMUI?

As a newcomer to Svelte and SMUI, I recently explored the official documentation at . I encountered some peculiar attribute declarations like "table$aria-label" and "input$autocomplete". The usage of dollar signs in naming conventions as well as the prefix ...

Place a material-ui React component at the center of a footer section

I'm facing a challenge with centering a material-ui Simple Breadcrumbs component within a footer as opposed to having it aligned to the left. Even though I'm new to this, I thought it would be straightforward but I can't seem to figure it ou ...

What is the purpose of the tabindex in the MUI Modal component?

Struggling with integrating a modal into my project - it's refusing to close and taking up the entire screen height. On inspection, I found this troublesome code: [tabindex]: outline: none; height: 100% How can I remove height: 100% from the ...

Looking for assistance with Redux and React Hooks - anyone?

I have created an interactive image gallery where users can click between page one and page two. When a user clicks on an image, a modal will appear displaying the selected image along with its title and description. There is also a Submit Button that allo ...

Exploring how to use React with a select component featuring objects

Hello, I am new to working with React and I have a question regarding the select component of Material UI. Here's my situation: I am creating functionality for creating and editing a User object. This User object has a primary key and some data, incl ...

Position a Paper component in the center of a div

I'm having trouble centering my <Paper> element inside a div. Can anyone help me with this? I have placed both the <Paper> and <RaisedButton> elements inside the div and applied the following CSS: .timerArea { text-align: center; ...

Challenge with Adding Padding to Icon and Label

https://i.stack.imgur.com/OSCnh.png Incorporating paddingtop to the Floating Label and positioning the DrawableRight Icon in the center. <android.support.design.widget.TextInputLayout android:id="@+id/input_layout_password" android:layout_wid ...

JSS questionings

While working with CSS in JS (JSS) and material-ui, I have encountered some challenges. I am able to inject styles effectively based on the context, but I am unsure of the additional benefits or features that it offers beyond style injection For example, ...

Incorporating a hyperlink into a keyboard input event

I am working on a form and I want to link a react-router Link to a key press event. Here is the structure of the form: <div className="col-md-6 col-md-offset-3" onKeyPress={e => this._handleKeyPress(e)}> <Paper style={styles.form}> ...

Change the filter items operator to "OR" from "AND"

Currently tackling the XGrid project, I'm faced with the task of filtering rows based on checkboxes selected on my page. I've been attempting to pass items into the filterItems prop to create multiple filters, but I'm struggling to figure ou ...

How to Align the Button Vertically with the TextField in React Material-UI

Utilizing the Material-UI library for React, I have been working on creating a simple form with the following design: https://i.stack.imgur.com/LY3ZN.png My challenge lies in aligning the button with the TextField element. Adjusting the margin-top proper ...

Having difficulty entering text into the Material UI TextField

I am encountering an issue with a button that opens up a Material UI Dialog containing a TextField. However, I am unable to click into the TextField to input any text. Additionally, when clicking on the button to open the Dialog, I receive the error messag ...

The process of implementing server-side rendering for React Next applications with Material-ui using CSS

I have developed a basic React application using Next.js with an integrated express server: app.prepare() .then(() => { const server = express() server.get('/job/:id', (req, res) => { const actualPage = '/job' const ...

Ways to minimize the space between objects

In the grid container below, an image is positioned on the left with a block of text on the right. There seems to be a large gap between the image and the text that I have attempted to reduce using various methods without success. Any suggestions on how ...

The Ultimate Guide to Setting Default Values in Material Ui Multiple Select Using React

I'm looking to populate multiple select options with specific values. Can someone assist with this? The valueSheet.userFullName array contains all user names, and I need to set some values for the dropdown. Thanks in advance :)) export default functio ...

Tips for updating the asterisk color in Material UI Textfield label

Is there a way to change the color of the asterisk to red without having a separate label for the TextField? <TextField id="outlined-basic" label="Name" variant="outlined" required/> ...

Tips on choosing a button and applying custom styles with emotion styles in MUI

Looking to apply a margin-right to my button. Currently utilizing mui 5 with Button variant='contained'. I created a custom CSS style using the styled component in mui and targeted the Box. const Wrapper = styled(Box)({ display: 'flex&ap ...

Tips on sending an array to material-ui dataSource props

Currently utilizing material-ui for a component. I am facing an issue with the autocomplete component in material-ui where I intend to display a list of icon names along with the icons. When only passing MenuItem to dataSource, it results in an empty input ...