Can you explain how to set a title to align with the object on the far left within a Grid component using justify="space-between" in Material UI?

I am currently working on a Grid layout project that involves a Grid container with four Grid items. The first Grid item takes up the full width and contains a title, while the other three Grid items contain avatars. My goal is to align the avatars to the right side of the page and have the title positioned to align with the left-most avatar. However, there seems to be an issue where the title is further to the left than the avatars. Also, the number of avatars can vary, making it challenging to achieve the desired alignment. Can you assist me in ensuring that the left-most avatar and title align perfectly?

Below is the current result I am getting:

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

And here is the desired outcome:

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

Here is the code snippet I am working with:

import React from "react";
import { Grid, makeStyles, Typography, Divider, Avatar } from "@material-ui/core";


const useStyles = makeStyles((theme) => ({
  header: {
    paddingTop: theme.spacing(3),
    paddingBottom: theme.spacing(3),
    flexGrow: 1,
  },
}));

const Header = ({ padding }) => {
  const classes = useStyles();
  return (
    <>
      <Grid
        container
        item
        direction="row"
        justify="space-between"
        align-items="center"
        xs={12}
        className={`${padding} ${classes.header}`}
      >
        {/*Page title and description*/}
        <Grid item xs>
          <Typography variant="h1" component="h1">
            Page Title
          </Typography>
          <Typography variant="body1">
            This is a description of what the page is about
          </Typography>
        </Grid>
        {/*People container*/}
        <Grid item xs className={classes.smeSection} alignItems="bottom">
          {/*People profiles*/}

          <Grid container item justify="flex-end" alignItems="bottom">
            <Grid item xs={12}>
              <Typography variant="h5">People</Typography>
            </Grid>
            <Grid item>
              <Avatar/>
            </Grid>
            <Grid item>
              <Avatar/>
            </Grid>
            <Grid item>
              <Avatar />
            </Grid>
          </Grid>
        </Grid>
      </Grid>
      <Divider />
    </>
  );
};

export default Header;

Thank you for your assistance!

Best regards, Katie

Answer №1

It is easy to make mistakes and get lost in the code when continuously nesting flexbox components.

If I understood your requirement correctly, here is the code I used to achieve the layout:

import React from "react";
import { Grid, Typography, Divider, Avatar } from "@material-ui/core";

const Header = () => {
  return (
    <>
      <Grid container direction="row" align-items="center">
        {/*Page title and description*/}
        <Grid item xs={9}>
          <Typography variant="h1" component="h1">
            Page Title
          </Typography>
          <Typography variant="body1">
            This is a description of what the page is about
          </Typography>
        </Grid>
        {/*People container*/}
        <Grid container item xs={3}>
          {/*People profiles*/}
          <Grid container item>
            <Grid item>
              <Typography variant="h5">People</Typography>
            </Grid>
            <Grid container>
              <Grid item>
                <Avatar />
              </Grid>
              <Grid item>
                <Avatar />
              </Grid>
              <Grid item>
                <Avatar />
              </Grid>
            </Grid>
          </Grid>
        </Grid>
      </Grid>
      <Divider />
    </>
  );
};

export default Header;

In my opinion, using a combination of Grid for general layout and flexbox for aligning nested elements would be a better alternative.

UPDATE: After reviewing the new data you provided, I redesigned the layout using flexbox.

import React from "react";
import {
  Typography,
  makeStyles,
  Avatar,
  Card,
  CardHeader,
  Divider
} from "@material-ui/core";

const useStyles = makeStyles((theme) => ({
  root: {
    display: "flex",
    justifyContent: "space-between"
  },
  usersHeader: {
    marginLeft: theme.spacing(2)
  },
  personCards: {
    display: "flex"
  }
}));

const Header = () => {
  const classes = useStyles();
  return (
    <>
      <div className={classes.root}>
        <div>
          <Typography variant="h3" component="h1">
            Page Title
          </Typography>
          <Typography variant="body1">
            This is a description of what the page is about
          </Typography>
        </div>
        <div>
          <Typography className={classes.usersHeader} variant="subtitle">
            Users
          </Typography>
          <div className={classes.personCards}>
            <Card elevation={0}>
              <CardHeader
                avatar={<Avatar />}
                title="Person name"
                subheader="Person role"
              />
            </Card>
            <Card elevation={0}>
              <CardHeader
                avatar={<Avatar />}
                title="Person name"
                subheader="Person role"
              />
            </Card>
            <Card elevation={0}>
              <CardHeader
                avatar={<Avatar />}
                title="Person name"
                subheader="Person role"
              />
            </Card>
          </div>
        </div>
      </div>
      <Divider />
    </>
  );
};

export default Header;

CodeSandbox reproduction: https://codesandbox.io/s/condescending-cartwright-grxhj?file=/src/Header.js

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

Reactjs Screen is failing to refresh properly, consistently lagging by one loop when making updates

After updating a record that is displayed on the screen, I noticed that the changes were not reflected in the MySql database. Despite attempts to refresh the array and filter the results, the screen remained stagnant. Only after manually refreshing the bro ...

Dynamic Session ID Generation in Next.js integration with Express.js Server

I am using Next.js v14 for my frontend and Express.js for the backend. To protect certain routes in Next.js, I have implemented an authentication guard using middleware.ts export default async function middleware(request: Request) { const loginStatus = a ...

Adjusting the width of a Material UI drawer: Tips and tricks

Currently, I am working on implementing the Material UI drawer and anchoring it to the top of my page. It is functioning correctly, however, I am encountering an issue where I am unable to adjust the width of the drawer. Despite trying to update the width ...

The issue of responsive spacing (such as mb-lg-2 mb-sm-3, etc) not functioning as expected has been identified in Bootstrap

Previously in Bootstrap 4, these classes were effective. However, I am finding that they are not functioning properly in Bootstrap 5. Any insights as to why this might be happening? Note: d-block d-lg-flex , text-center text-lg-start text-md-end seem to s ...

The absence of the 'classes' property in the MUI component type is causing an issue in Typescript Material UI

Simply put, typescript is giving me a hard time by complaining about the missing property classes on every material-ui component. Essentially, Typescript requires the presence of the classes property in nearly all material-ui components. Here is the error ...

The useEffect function is repeatedly making API calls within a component, despite not having any dependencies specified

As a newcomer to React.Js, I'm encountering an issue with useEffect repeatedly calling an API without any specified Dependency. Is there another approach I should consider? The relevant file is located at: /pages/dashboard/speaking/[slug].js } else i ...

Issue with CSS styling on a content slider causing the last picture to display incorrectly

I recently updated a Content Slider and tweaked the styles to my preference. Check out the changes I made on this link. In addition, I included an extra Thumbnail Picture on the right (7th one) along with the Main Picture. Oddly enough, the Slider seems ...

Adjust the alignment of text to a precise vertical ratio of the image

Let's say I have this amazing logo with some artistic text in it that cannot be replicated using a downloaded WebFont In the image, the text baseline sits at 68% from the top and 32% from the bottom. Now I want to align text in an HTML document, whi ...

Trouble presenting information retrieved from API

I'm encountering an issue with displaying the data I fetched from an API. I'm not sure what's causing the problem... I attempted to use the map() function to access the data, but it's not functioning as expected either. import React fr ...

What is the best way to incorporate multiple theme parameters in Material App Flutter?

In my flutter application, I have a standard MaterialApp Widget. Now, I am looking to include multiple theme parameters in it... For example:- theme: ThemeData(fontFamily: kGetAppFont(context, languageCode)), theme: ThemeProvider.themeOf(themeConte ...

The process of styling with styled components in Mui - a guide to styling

Currently, I am facing challenges with styling and organization while working on a new react project with material ui and styled components. Despite researching best practices for styled components, I am still struggling to find an effective solution for s ...

Issue with Bootstrap 4 Navbar collapsing and not expanding again

Help needed! My navigation bar collapses when the window is resized, but clicking on the hamburger icon does not open it back up. I have included my code below. Can someone please provide guidance on how to expand the collapsed navbar? <html lang=&quo ...

"Create a table with rows that automatically adjust to the same height, regardless

Is there a way to create a table where the height remains constant regardless of the number of rows added? For example: https://i.sstatic.net/zJNqD.png Even if rows are added, I want the height to stay consistent. I cannot use percentage since the numb ...

Exploring the use of color in text embellishments

Is it possible to change the color of the underline on text when hovering, while keeping it different from the text color? I have successfully achieved this in Firefox using the property "-moz-text-decoration-color". However, this does not work in other m ...

Unable to locate: NextAuth.js within the application directory of Next13

Can someone please help me out? I have a package "next": "13.2.4", "next-auth": "^4.20.1", "react": "18.2.0", that includes a submit function to register users async function onSubmit(values: an ...

Instructions on invoking a function from another Material UI TypeScript component using React

In this scenario, we have two main components - the Drawer and the AppBar. The AppBar contains a menu button that is supposed to trigger an event opening the Drawer. However, implementing this functionality has proven challenging. I attempted to use the li ...

Unable to integrate Material-UI into a React application within a Visual Studio C# ASP.NET Core Web Application

When setting up a new .NET Core web application with the React and Redux template, everything seemed to be running smoothly until I tried to install the Material-UI library in my ClientApp folder for the react project. Upon importing a component from the l ...

Highcharts: Show tooltip above all elements

Is there a way to configure tooltip display above all elements? I want to define specific coordinates so that the tooltip remains open even if it is covering the chart, and only closes when interacting with the top block. Screenshot 1 Screenshot 2 For e ...

Shifting Elements - Navigation triggers subtle movements in CSS styles as you move across pages

I've noticed a strange issue on my website where certain elements seem to be shifting slightly when navigating between different pages. Here's a quick video clip demonstrating the problem. It appears that these elements are not staying static as ...

Outside drop shadows in CSS3 creates an interesting visual effect by giving

I am currently using the following CSS styling for a list of li items. border: 1px solid black; border-radius:10px; box-shadow: 8px 8px 4px #666; -o-box-shadow: 10px 10px 5px #888; -icab-box-shadow: 10px 10px 5px #888; -khtml-box-shadow: 10px 10px 5px #8 ...