Tips on how to horizontally align an icon and text using Material UI

As a newcomer to Material UI, I am facing an issue where my icon and text are not aligned:

What I'm aiming for:

This is the code I have so far:

<div style={{
    display: 'inline-flex',
    VerticalAlign: 'text-bottom',
    BoxSizing: 'inherit',
    textAlign: 'center',
    AlignItems: 'center'
}}>
    <LinkIcon className={classes.linkIcon}  />
    revolve
</div>

I've attempted using grid and row layouts, but none seem to do the trick. Can anyone offer some guidance?

Answer №1

This solution works flawlessly!

<div style={{
    display: 'flex',
    alignItems: 'center',
    flexWrap: 'wrap',
}}>
    <LinkIcon />
    <span>rotate</span>
</div>  

Material-UI now offers components that handle this situation more effectively without the need for inline styles:

import Typography from '@mui/material/Typography';
import Stack from '@mui/material/Stack';

<Stack alignItems="center" direction="row" gap={2}>
  <LinkIcon />
  <Typography variant="body1">Rotate</Typography>
</Stack>

Answer №2

You can easily accomplish this in the latest version of MUI, MUI v5, by utilizing a combination of a Stack component and adjusting the alignItems prop to center:

import Stack from '@mui/material/Stack';
import Typography from '@mui/material/Typography';
import AddCircleIcon from '@mui/icons-material/AddCircle';
<Stack direction="row" alignItems="center" gap={1}>
  <AddCircleIcon />
  <Typography variant="body1">text</Typography>
</Stack>

https://codesandbox.io/s/51940157-how-to-align-horizontal-icon-and-text-in-material-ui-uu2y5?file=/demo.tsx

Answer №3

To achieve this layout, Grid is the way to go. Here is an example of how you can implement it:

<Grid container direction="row" alignItems="center">
  <Grid item>
    <LinkIcon className={classes.linkIcon} />
  </Grid>
  <Grid item>
    revolve
  </Grid>
</Grid>

Answer №4

Check out the code snippet below. Feel free to customize the variant based on your specific needs.

const customStyles = makeStyles(theme => ({
  iconContainer: {
    verticalAlign: 'middle',
    display: 'inline-flex'
   }
}));

<Typography variant="subtitle1" className={classes.iconContainer}>
    <LinkIcon className={classes.linkIcon}  /> rotate
</Typography>

Answer №5

Here is an alternative and straightforward approach:

<Container direction="row" alignItems="center">
     <SearchIcon /> example
</Container>

Answer №6

design

const design = theme => ({
    icon: {
        position: "relative",
        top: theme.spacing.unit,
        width: theme.typography.display1.fontSize,
        height: theme.typography.display1.fontSize
    }
});

JSX

<Typography variant="display1">
    <Icon className={this.props.classes.icon}/>Your&nbsp;Text
</Typography>

you have the option to substitute display1 with display3 or any other typography variant in all 3 occurrences to adjust your text size. The &nbsp; ensures that your text remains intact when it wraps.

This can be displayed as shown below

https://i.stack.imgur.com/jjp1F.png

using display3 along with a few additional styles for color enhancement.

Answer №7

When you place ListItemIcon and ListItemText inside a ListItem, it ensures that they stay on the same line and do not break:

import ListItem from '@material-ui/core/ListItem';
import ListItemIcon from '@material-ui/core/ListItemIcon';
import ListItemText from '@material-ui/core/ListItemText';
    
<ListItem >
  <ListItemIcon><AccessAlarmIcon color="secondary" /></ListItemIcon>
  <ListItemText>Last updated: 1 hour ago</ListItemText>
</ListItem>

Check out this demo image:

Answer №8

You have the option to utilize Material UI's Flexbox component.

Here is a sample:

// ...
import { Box } from '@material-ui/core';
// ...

<Box alignItems="center" display="flex">
 <Box>
    <LinkIcon className={classes.linkIcon}  />
 </Box>
 <Box>
    revolve
 </Box>
</Box>

The alignItems: center attribute ensures vertical alignment of the internal items.

This will introduce some additional HTML elements. Nevertheless, through the component's API, you gain access to numerous customization options. For instance, there are methods to apply margin or padding consistently with your Material UI design. Additionally, adjusting item alignment based on specific needs is straightforward.

Answer №9

To include these, simply add them at the beginning

import { Grid, Typography } from "@material-ui/core";
import LinkIcon from "@material-ui/icons/Link";

You can utilize them like so:

<Grid style={{ display: "flex" }}>
    <LinkIcon />
    <Typography>Rotate</Typography>
</Grid>

Take a look at this working example on CodeSandbox Here

Answer №10

To achieve vertical alignment of text and icon within MUI's Typography without relying on the variant attribute, you can opt for a simple solution by applying a display property directly to the Typography component:

<Typography display="flex">
    Hello!
    <Icon />
</Typography>

This method proved effective in my case.

Answer №11

All of the solutions have been reviewed, and I believe this is the most straightforward one:

<Typography><LinkIcon sx={{verticalAlign:"middle"}}/> RESOLVE</Typography> 

This solution also supports inline images for aligning them with text.

Answer №12

Encountering a similar issue, here is my approach:

import LinkIcon from '@material-ui/icons/Link';
import styled from 'styled-components';
...
const Resolve = styled.div`
  display: flex;
  vertical-align: middle,
`;

<Resolve>
  <LinkIcon style={{ marginRight: '5px' }} />
  <p>resolve</p>
</Resolve>

If the default mUI link icon doesn't meet your needs, you can create your own:

{/* this is the same chained icon used in own material-ui library, 
not sure why it's not available yet */}

function CustomLinkIcon(props) {
  return (
    <SvgIcon {...props}>
      <path d="M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14....
...
<Resolve>
  <CustomLinkIcon 
     {/* adjust margin top if needed */}
     style={{ marginRight: '3px', marginTop: '3px' }} {
  />
  <p>resolve</p>
</Resolve>

Answer №13

One recommended approach is to utilize it in the following manner:

  import {Box, Typography} from '@material-ui/core'
  import LinkIcon from '@material-ui/icons/LinkIcon';

   ........

   <Box display='flex' alignItems='center'>
       <LinkIcon className={classes.linkIcon}  />
       <Typography variant='h5'>
          resolve
       </Typography>
    </Box>

Answer №14

By using this solution, the icon will seamlessly blend with your typography style, eliminating the need to constantly rewrite the style when making changes

<Typography component={Stack} direction="row" alignItems="center" color="secondary">
     <EditIcon fontSize="inherit" sx={{ marginRight: 1 }} />
     Edit
</Typography>

Answer №15

Utilizing Typography to achieve precise horizontal alignment with icons

const customStyles = theme => ({
    icon: {
        fontSize: '1rem',
        position: 'relative',
        right: theme.spacing(0.5),
        top: theme.spacing(0.5),
    },
});


<Typography><CheckCircleIcon className={className={this.props.customStyles.icon}}/>Home</Typography>

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

Is it possible to schedule deployments using Vercel Deploy Hooks in Next.js?

When we schedule a pipeline on git, I want to schedule deploy hooks on vercel as well. Since the app is sending getStaticProps and every HTTP request will be run on every build, I have to rebuild the site to get new results from the server. For instance, ...

Linking to a Different Tab without Tab Mutation with Bootstrap 3.3.5

I am facing a similar issue to the mentioned questions. I am trying to use a link to change tabs, but the problem is that the link only changes the tab content and not the active tab. The most similar question can be found at: Bootstrap linking to a tab w ...

Is it feasible to incorporate an external library as a script within a class or functional component in React?

Welcome and thank you for taking the time to read this question! I am currently working on a project where I need to load a TIFF image. After researching, I found a library that can help with this task: https://github.com/seikichi/tiff.js There is also ...

What's the best method for concealing components: using a class to hide or removing them from the

I am encountering difficulties in React as I try to add a class to a component after a specific time duration. My goal is to apply the "hidden" class to a loading image, changing it to display: none after a few seconds. However, despite my efforts, I keep ...

Input form with multiple fields. Automatically display or hide labels based on whether each field is populated or empty

I am attempting to create a form where the placeholders move to the top of the input when it is focused or filled. However, I have encountered an issue with having multiple inputs on the same page. Currently, my JavaScript code affects all inputs on the pa ...

Having trouble with NextJS not updating state upon button click?

I am encountering a problem with my NextJS application. I am attempting to show a loading spinner on a button when it is used for user login. I have tried setting the `loading` state to true before calling the login function and then reverting it to fals ...

The Autocomplete field's label remains visible even after the form is submitted

I am currently developing a feature that allows users to select an option in the Autocomplete component. In the parent component, I pass these props: const filterDropdownConfig: FilterSelectAutocomplete = { data: scenariosList, label: { className: &apos ...

Exploring the Issue with SWR Hook in Next.js using TypeScript

Seeking assistance with the SWR hook as I navigate through some challenges while attempting to use it effectively. This time, the issue appears to be minor. The objective is to set a breakpoint in my API to retrieve data, using axios. The problem arises ...

Displaying an array of JSON objects in ReactJS by parsing them

Recently, I've encountered an odd issue with my React App. I am attempting to parse a JSON object that includes arrays of data. The structure of the data looks something like this: {"Place":"San Francisco","Country":"USA", "Author":{"Name":"xyz", "Ti ...

The PHP file I'm trying to access isn't receiving the GET request from my PHP script

Basically, I want a button on one php page to trigger the printing of a new php page. This feature is working perfectly. The only issue is that I am trying to ensure the user ID gets passed over to the second page and displayed there. Strangely, it seems t ...

Utilizing Wordpress post images to dynamically change background URLs in CSS

Is there a way to dynamically set a background image in CSS using PHP, specifically the Wordpress post image? background: <?php if(has_post_thumbnail()){ $img = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'dest ...

What is the best way to deactivate a button when a certain input field is left blank?

I'm having trouble figuring out how to deactivate a button when specific input fields are empty, while others can remain optional for the process. In my course, we were taught to disable the button until all inputs are valid, so I'm a bit confus ...

Can you guide me on implementing a transition animation through class toggling?

I am facing an issue where certain elements need to be highlighted or unhighlighted conditionally. To achieve this, I have assigned a class called highlight to the elements that require highlighting with a transition animation. The challenge arises when t ...

Challenges of Using Flexbox in Media Queries

How can I use flex boxes in CSS to ensure that from a min-width of 769px to 1025px, the third figure is displayed on a new line while the first and second figures remain on the top line taking up equal space? <div class="mid-col-section-2"> <figu ...

A workaround for background-size in Internet Explorer 7

Currently, I am working on a project at this link: Everything seems to be functioning well in Firefox and Chrome, however, I have encountered an issue with the background-size property not being supported in IE7. I heavily rely on this property throughout ...

Error: Attempting to access the 'getProvider' property of an undefined variable

I am encountering an error that says "property of undefined (reading getProvider)" while deploying my function to Firebase. I am currently trying to figure out how to obtain the auth instance. When I attempt to use firebase.auth, it results in another er ...

Steps for designing an HTML table that expands and collapses partially

I am currently revamping an old "Top Screens" page by expanding the display from the top 30 to the top 100 in a basic html table format. However, I only want to show the top 20 on page load with an expand/collapse feature. While I have come across examples ...

Exploring for JSON keys to find corresponding objects in an array and adding them to the table

I'm currently working on a project where I need to extract specific objects from a JSON based on an array and then display this data in a table. Here's how my situation looks: playerIDs: number[] = [ 1000, 1002, 1004 ] The JSON data that I am t ...

Determine whether a WebElement contains a particular content within the :after pseudo class

After locating my element in Selenium, I've come across an interesting challenge. IWebElement icon = box.FindElement(By.ClassName("box-icon")); Sometimes, this element (icon) has a content set as follows: &:after { content: $icon-specia ...

Surprising pause in the menu transition animation

Currently, I am in the process of developing a menu that seems to have some flaws. One issue is that it appears a bit choppy, but the more concerning problem is the half-second delay after clicking an item before it animates. The concept behind this menu ...