Angular-Material2: Align text and md-icon vertically to match vertical style?
I utilize the inline
attribute. This will cause the icon to correctly scale with the size of the button.
<button mat-button>
<mat-icon inline=true>local_movies</mat-icon>
Movies
</button>
<!-- Link button -->
<a mat-flat-button color="accent" routerLink="/create"><mat-icon inline=true>add</mat-icon> Create</a>
I add this to my styles.css
to:
- solve the vertical alignment problem of the icon inside the button
- material icon fonts are always a little too small compared to button text
button.mat-button .mat-icon,
a.mat-button .mat-icon,
a.mat-raised-button .mat-icon,
a.mat-flat-button .mat-icon,
a.mat-stroked-button .mat-icon {
vertical-align: top;
font-size: 1.25em;
}
This is a common issue when using <md-icon>
. To align the icon and text, you can put your text inside a span and apply style to that:
<div>
<md-icon>home</md-icon><span class="aligned-with-icon">Sample Text</span>
</div>
In your component.css:
.aligned-with-icon{
position: absolute;
margin-top: 5px;
margin-left: 5px; /* optional */
}
You can also use relative
position if you'll be putting multiple icons in the same div. Here is the css for that:
.aligned-with-icon-relative{
position: relative;
top: -5px;
margin-left: 5px; /* optional */
}
Another option is to use flex
display on the outer div and align-items
to center
:
In your html:
<div class="with-icon">
<md-icon>home</md-icon>Sample Text
</div>
In your css:
.with-icon {
display: flex;
align-items: center;
}
Here is a Plunker Demo
You can use
div {
display: flex;
vertical-align: middle;
}
or
span {
display: inline-flex;
vertical-align: middle;
}
This can be achieved using CSS flexbox
<!-- HTML part -->
<div class="outer-div">
<mat-icon>home</mat-icon>
<span>Home</span>
</div>
<!-- CSS part -->
.outer-div {
display: flex;
flex-direction: column;
align-items: center;
}
.outer-div > span {
font-size: 10px;
}