How to align horizontal icon and text in Material UI
To pop an icon and text into a nice, neat horizontal alignment in Material UI, put them into a Box
setup on display: flex
with alignItems: center
:
Just like that, your icon and text will chum up, centered and inline. Isn't flex the best wingman around?
Different approaches for alignment
Using the Stack component
If you're using Material UI v5, the Stack
component will be your best friend. It's straightforward, clean, and handles alignment like a pro:
The Stack
component brings the tidiest trio: direction, alignItems, and gap properties. They all work together to make your design responsive and accessible.
Alignment with Grid system
Another route to an elegant alignment is through Grid
component. It gives you more control over your layout:
The magic here is that you can control spacing and alignment precisely, transforming even complex layouts into a walk in the park.
Inline Icons with Typography
If you want to keep it real simple, just nest your icons within Typography elements for an inline display that's easy on the eyes:
Here, icons and text share the same typography properties. Drama-free alignment is the best kind, isn't it?
Responsiveness and wrapping
Handling wrapping with flexWrap
Are you looking to make your content more adaptive? Then reach for flexWrap: 'wrap'
:
Just like that, your elements remain aligned but can migrate to a new line on smaller screens. It's like herding cats, but easier.
Customizing with makeStyles
Sometimes, the off-the-shelf styles just won't do. For those times, try makeStyles
:
Custom styles can be applied to text and icons alike, giving you a higher degree of control over your visuals.
Practice with CodeSandbox
The best way to learn is to roll up your sleeves and get your hands dirty. Try out these tips in a CodeSandbox example — a practical, interactive demo is a brilliant tool to beef up your understanding.
Was this article helpful?