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.

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

Exploring the React component life cycle: Understanding the distinction between render and return, and what happens post-return

This question pertains to the concepts surrounding react component life cycles. Below is an example code snippet provided as a general reference. const Modal = ({ className, variant, width, withCloseIcon, isOpen: propsIsOpen, onClose: tellParen ...

Tips for including additional properties to a <button> element using ReactJS and Typescript

Currently, I am in the process of creating a unique component which consists of an ordinary <button> tag and has a new prop called aria-current. The issue at hand is that Typescript is flagging an error stating that this property does not exist with ...

A guide on utilizing the useState hook to tally occurrences of elements within an array - specifically within React's useState hook

Currently, I am tackling an exercise that involves an array containing 10 objects. Each object has properties like txt and color, for example: arr = [{txt: "txt1", color: "red"}, {txt: "txt2", color: "green"}, {txt: ...

Chrome: Box-shadow not visible on images with a background present

Recently, I have noticed an issue with the box-shadow not displaying on images with a background on my website. This problem started occurring in Chrome a few months ago, despite working perfectly fine around six months ago. To pinpoint the problem, I cre ...

Bring a div box to life using AngularJS

Struggling to animate a div-Box in AngularJS? Despite trying multiple examples, the animation just won't cooperate. I'm aiming to implement a feature where clicking on a button triggers a transition animation to display the search form. I under ...

What is the method for styling the third list item in a CSS hierarchy?

I'm struggling to understand the hierarchy in CSS for creating this specific layout. I've searched for explanations, but haven't found a clear one that breaks down how each level works. This is my first time working with CSS so it's bee ...

An easy way to attach a Contextmenu to a specific element

I have implemented a scrolling feature for one of the div elements in my Application. Inside this div, there is a templated table with over 100 rows. Users are able to add or delete rows using a contextMenu. The contextMenu offers 4 options - AddTop, AddB ...

the async function fails to run

fetchData = async () => { try { //Accessing data from AsyncStorage let car = await AsyncStorage.getItem('CAR') this.state.DatabaseCar=[]; this.state.DatabaseCar = JSON.parse(car); alert(this.state.Da ...

Error in Heroku deployment - Express and React app displaying a white screen

I am encountering a challenging situation as I attempt to understand the issue at hand. Following the deployment of my React/Express application on Heroku, the build and deployment proceed without errors, but the React frontend appears blank. The browser ...

Arranging two divs side by side while considering a responsive theme

My struggle with aligning divs side by side continues. After searching through online forums for hours, I have yet to find a solution. The goal is to create a collage using six images. However, currently all the images stack vertically on the left side on ...

Issue with CSS: Dropdown menu is hidden behind carousel while hovering

I'm struggling with adjusting the position of my dropdown list. It keeps hiding behind the carousel (slider). When I set the position of the carousel section to absolute, it causes the navbar to become transparent and the images from the carousel show ...

The issue with clip-path not functioning correctly in Safari persists

My list of clipped elements is causing an issue when using the CSS3 clip-path method to clip an image into an SVG path. The clipping works perfectly, but in Safari (V 12.1.4), the position of the clipped element changes with each box. The element ...

Unable to locate Babel plugin

I keep encountering an error with Babel saying Cannot find module 'babel-plugin-svg-sprite-loader' This is the content of my babel configuration file: { "presets": ["next/babel"], "plugins": [ ["sty ...

The input focus placeholder at the top is not functioning properly when applied to an input field that

I recently designed an input box similar to this: https://i.stack.imgur.com/lkSnh.png However, I encountered an issue when trying to make the input box readonly. Here is a snippet of my code: .myinput input:focus { outline: none; } ... <div clas ...

Having trouble getting the onPress event to function properly on a custom button component in my React Native application

As a React Native beginner, I am currently working on a project where I am trying to create a custom button named "RoundedButton" using TouchableOpacity. However, when I attempt to trigger an event using onPress like , it does not seem to work for me. Here ...

Creating a dynamic full-width background image that adjusts its height according to the content: a step-by-step guide

Currently, I'm attempting to apply a background image to a webpage that spans 100% width in order to adjust to the viewport size. The method I am using involves placing an image directly after the body tag with the subsequent styling: img#background ...

Guide to activating the isActive status on a live link within a map iteration utilizing the NEXTUI navigation bar

Check out the new NEXTUI navbar I'm using: I am having trouble setting the isActive property on the active link in my NavBar component in Next.js. I couldn't find much help on Google, so I'm hoping someone here has experience with this or k ...

There seems to be an issue with the compatibility between Material UI and Next.js

When working with Next.js and Material UI, I encountered some challenges despite following the methods outlined in the Material UI documentation. An error occurs when using props with makeStyles: https://i.stack.imgur.com/5n2Zm.png I face issues when pa ...

Using the / (forward slash) in CSS styling statements

Similar Query: Understanding the CSS font shorthand syntax As I was examining the styling on Apple's website, I encountered a CSS rule that left me puzzled: body { font: 12px/18px "Lucida Grande","Lucida Sans Unicode",Helvetica,Arial,Verdana, ...

scala-js-react: Surprising variation between Ajax request methods GET and DELETE

My Ajax code for handling GET and DELETE operations in scalajs-react looks like this: DELETE: val ajax = Ajax("DELETE", "http://localhost:8081/delete/"+id) .setRequestContentTypeJsonUtf8 .send("") .onComplet ...