What is the best way to center my items vertically in a material-UI Grid row?

Struggling to vertically align three items in a row using Material UI's Grid component. Despite setting "justifyContent: 'center'," it only horizontally centers the items. Here are my styles:

const styles = (theme) => ({
  root: {
    textAlign: "left",
    margin: theme.spacing(2),
    paddingBottom: theme.spacing(1),
    color: theme.color.secondary,
  },
  cardHeader: {
    paddingBottom: theme.spacing(0),
  },
  cardContent: {
    width: "100%",
    paddingBottom: theme.spacing(1),
  },
  rowBody: {
    width: "100%",
    flexWrap: "nowrap",
    alignItems: "center",
    justifyContent: 'center',
  },
...
      <CardContent className={classes.cardContent}>
        <Grid container className={classes.rowBody} spacing={1}>
          <Grid item>
            <img height="20" src={require('../../img/apple.svg')} alt="" />
          </Grid>
          <Grid item>
            {title}
          </Grid>
          <Grid item className={classes.infoIcon}>
            <InfoIcon />
          </Grid>
        </Grid>

Output shown below.

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

Looking for a way to vertically align items without affecting horizontal alignment.

Answer №1

When using Svg and img elements, they are set to have a display of inline-block by default. This can cause a bottom gap to appear. To get rid of this gap, simply change the display property to block.

To see an example of this in action, check out my CodeSandbox demo.

Answer №2

[Update]: After reviewing Kiril's response and experimenting in the sandbox, I have come up with a new approach:

import React from "react";
import { Grid } from "@material-ui/core";
import { Error } from "@material-ui/icons";

export default function App() {
  return (
    <Grid container spacing="1" alignItems="center">
      <img
        src="https://yt3.ggpht.com/a/AATXAJxK3dHVZIVCtxjYZ7mp77wBbCs9fw4zU46V_Q=s288-c-k-c0xffffffff-no-rj-mo"
        alt="no-src"
        height="20px"
      />
      <span style={{ padding: 5 }}>no title supplied</span>
      <Error />
    </Grid>
  );
}


Have you considered placing all three elements within the same grid? This could simplify your code and resolve any issues.

If not, your grid might be aligned but the content isn't due to it not being a direct child of a flex container. You can try adding

display: table-cell; verticalAlignment:center
to your grid item (or its content by wrapping it in a div with width and height set to 100%)

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

Guide to Returning a Unique Error Message when Verifying Credentials with Next-Auth v5.0.0-beta.5

Currently, in my nextJs app, I am using [email protected] for user authentication. I am looking to implement custom error handling for failed user authentication with credentials. In the past, I was able to achieve this functionality with the followi ...

Ensure that divs can adjust in size while maintaining the same dimensions of their contained

I'm currently facing a slight issue with these two divs. I want them to be scalable, which I know can be achieved by using percentages, but every time I do so, the divs end up out of position. When I try setting widths, they look fine in Google Chrome ...

What are some recommended techniques for retrieving data following a post request in a Node.js environment?

I have a form in Node where I can input user information. After submitting the form, a post request is triggered to add the user to the database. How can I efficiently fetch the data to display a new list of users on the user list? Should I include a get ...

What is the best way to position this sidebar on the right instead of the left?

I am having trouble implementing a responsive sidebar with a toggle icon. I found one on Codepen, but it is currently aligned to the left. How can I align it to the right? I have been searching through the code and have tried using text-align and justify- ...

Error: Attempting to access 'pageContext' property on undefined object, resulting in TypeError while utilizing sp pnp v3

I am currently following a tutorial to build a webpart using SPFX and SP/PNP v3: https://learn.microsoft.com/en-us/sharepoint/dev/spfx/web-parts/guidance/use-sp-pnp-js-with-spfx-web-parts I have also consulted: Here is the main .ts file: public async onIn ...

How can I anchor a div Banner saying "Get 50% off our products" to the Navbar directly above it?

Bootstrap Question: How can I attach the div Banner ("50% off of our products") to the Navbar directly above it? The structure looks like this: <Navbar> </Navbar> <div> <span>Discount: 50% off of our products </span </di ...

The innovative technique of using pure CSS to secure the bottom edge of a div to the viewport

Is there a way to keep two container divs positioned x pixels from the bottom of the viewport without using position absolute|fixed? I want them to remain as position: relative for proper DOM flow. Searching for a CSS-only solution that works in IE7+. Mos ...

I'll show you how to implement custom fonts in TailwindCSS and NuxtJS!

Currently, I am in the process of developing a website using NuxtJS along with Tailwind CSS for styling. To incorporate my desired fonts, I have utilized the @nuxtjs/tailwindcss module. Despite applying the correct font-family through CSS, it seems that m ...

What sets apart a React component from a function-as-component in React?

React is really confusing to me right now. Take this simple react component for example: export default function Foo(){ return( <div> <div>some text</div> </div> ) } I want to add a child compone ...

Tips for effectively transmitting JSON data through SuperAgent within the React framework

Currently, I am transmitting the state of my react app to a server that is not located on the same server as the frontend. request.post('http://localhost:8000/guide') .send(JSON.stringify(this.state)) .end((err, resp) =&g ...

Increase the gap between columns in Bootstrap for a better layout

I have implemented a web layout using bootstrap 3. You can view the JSFiddle here. In order to make the layout responsive, I had to structure it in a slightly unconventional way. The final output on small screens includes three information boxes within an ...

Implementing the React factory pattern for enhanced efficiency

Imagine I have this simple component called A. I want to keep the rendering logic separate from the data manipulation in this component. All I need is to input some raw data and have it displayed. What would be the most React-friendly approach to achieve ...

How can I customize the calendar background color in react-datepicker?

I need to customize the appearance of the popper (which is a calendar) in my react-datepicker by changing the background color to black and font color to white when switching themes from default (white) to black. Although I have attempted to use popperCla ...

The values obtained from the previous parameter object of the React setState hook can vary and are not always

In my code, I am using a useEffect hook to update the state with setState. However, I'm encountering some unusual and inconsistent behavior with the previous parameter: useEffect(() => { setCurrentPicturesObject((existing) => { ...

Can a `react` app with `mysql` be uploaded to `github`?

I recently created a basic online store with the help of react, node, and mysql. I am considering uploading it to github, but I'm uncertain if I can do so while my database is currently stored on localhost. Any advice? ...

Steps for including a solid bottom border in a toggled navigation bar that is responsive

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document&l ...

Exploring ReactJS: Understanding State and Local Variables

Reference: For more information on ReactJS state and lifecycle, visit this link In the assignment this.timerID = setInterval, is the variable timerID just a regular variable or should it be considered as part of the component's state? Why isn't ...

Tips to center a circular progress bar in Material UI

Does anyone know how to properly center-align a circular progress bar in a login form using material UI? I'm having trouble with it not being positioned correctly: screenshot {isLoading && <CircularProgress />} {user?.ema ...

Insider knowledge within Nextjs client construction

NextJs has a feature where secrets are categorized as client and backend secrets, according to the documentation. It states that if you prepend the variable with NEXT_PUBLIC_, it will be included in the frontend bundle. You can find more information about ...

There was an error encountered during the installation process of next.js

Whenever I type in the command: npx create-next-app It prompts me to enter a directory name, and when I do so and hit enter, it just hangs at that point. https://i.sstatic.net/S632N.png In the past, when I used 'create-next-app' with npm like ...