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

The modal in Bootstrap V5 refuses to hide using JavaScript unless the window method is utilized

Currently in the process of developing a react application and utilizing standard bootstrap. The command to display a modal and switch to one is functioning properly; but, the command to hide the modal does not work unless I establish it as a property on t ...

What are the steps to insert a plotly graph into a webpage so that it responds to different

I have been working on integrating a plotly pie chart into my website. In order to make the iframe responsive, I decided to utilize this specific tool to generate the necessary html/css. While the chart appears satisfactory on a laptop screen, it is barely ...

Eliminating the Skewed Appearance of Text in Input Fields Using CSS

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Customized Page Layout</title> <script src="https://c ...

Problem with Typescript: The type '{ x;y }' is required to have a '[Symbol.iterator]()' method

Just starting out with Typescript and tackling the task of converting a React project from JavaScript to TypeScript. I've been diving into various posts for guidance, but I feel like I'm going in circles. Any assistance would be greatly appreci ...

Creating a notification feature for an HTML application

I am in the process of creating an HTML app through intel XDK. While I understand that using HTML to build apps is not as common, it is the language I am most familiar with, along with CSS. One feature I would like to include in my app is a weekly notific ...

Assigning a value to an input field using jQuery

I'm facing an issue while trying to set the value for an input using jQuery. Essentially, when you click on a link, it redirects you to a different page with a form, and I am attempting to set the value of one of the inputs in that form. Unfortunately ...

Incorporating CSS into an HTML page created by a Python CGI script

Last week, I was handed a Python-based monitoring and notification tool to work on. My task is to develop a proof of concept dashboard using the data collected by this tool over the years. The catch is that I'm fairly new to Python and have never dabb ...

Having trouble with uploading images on Amazon S3 and sharing them on Facebook? Learn how to set the correct meta tag "og:image" in Next

As I work on coding to enable sharing my website page on Facebook, I have utilized meta tags for open graphs. Previously, the images were stored on the server and linked in the meta tag like this: <meta key="og:image" property="og:image" content ...

Is there a way to use flexbox to decrease the size of images?

Struggling to make my code mobile-friendly. The PC version looks good, but on mobile, the bio stretches and text goes off the page. I can't seem to get the picture to shrink when viewed on a mobile device, or have the content neatly boxed alongside it ...

Interactive Component overlying Layer - HTML/CSS

Currently, I am working on a web application that features a navigation bar at the bottom of the screen. To enhance visibility, I decided to apply a linear gradient overlay above the underlying elements. This screenshot illustrates what I mean. However, I ...

Is there a way to incorporate the value of `undefined` into a React Material-UI Autocomplete?

I am facing a scenario where I would like the user to choose between true, false, and undefined: const [value, setValue] = useState<boolean | undefined | null>(null) <Autocomplete options={[true, false, undefined]} value={value} rende ...

Encountering a problem when trying to launch the React application

I encountered an error while running the "npm start" command after creating a React app using npx create-react-app my-app. 0 info it worked if it ends with ok 1 verbose cli [ 1 verbose cli 'C:\\Program Files\\nodejs\\ ...

Ways to resolve the error: TypeError - Unable to retrieve the 'user' property as it is null

I attempted to create a duplicate of the state, make changes to the copy, and then assign it back to the state. However, I encountered an error in the process. Below is the code snippet: class App extends Component { constructor(){ super() this ...

How can we simplify this React component to reduce its verbosity?

After creating a test project to delve into react, react-router and react-redux, I revisited the Settings.jsx file. Now, I am pondering on how to streamline it and reduce potential errors. import React, { Component } from "react"; import { connect } from ...

Clicking will cause my background content to blur

Is there a way to implement a menu button that, when clicked, reveals a menu with blurred content in the background? And when clicked again, the content returns to normal? Here's the current HTML structure: <div class="menu"> <div class=" ...

Why isn't the class applying the color to the Angular span element?

My Angular application generates text that needs to be dynamically colorized. To achieve this, I inject a span element with a specific class into the text output like so: Some text <span class="failResult">that's emphasized</span> and oth ...

The ngbDatepicker within the Bootstrap angular framework is designed to seamlessly integrate with ngbPanelContent without causing overflow issues

I've integrated the ngbDatepicker into a form as shown below <ngb-panel> <ng-template ngbPanelTitle> <div class="row"> <ui-switch (change)="onChange($event,2)" [checked]="profession ...

What causes useEffect to be triggered multiple times, even when it is dependent on another useEffect function that is being executed repeatedly?

I have a specific requirement that involves using two useEffect hooks. First useEffect is used to set the latitude and longitude in the state with an empty dependency array. useEffect(() => { navigator.geolocation.getCurrentPosition(geo = ...

International component dominates over other elements

While working with the Next.js framework, I encountered an issue where the clipped drawer from MUI was obstructing other page contents. To address this, I decided to include the drawer component in the _app.tsx file as shown below: import '../styles/g ...

Is there a way to retrieve user input without having to submit the form?

I am looking to capture user input without the need for submission, and then pass it through an AJAX method as a parameter to an action. Despite trying various methods, I have not been able to find a solution. Below is the code snippet: <input type="t ...