Home > OS >  Center the center of an Angular Material icon
Center the center of an Angular Material icon

Time:10-29

I am trying to center an Angular Material icon in a rectangle:

enter image description here

As shown in the picture, the icon is (more or less) centered; however, it's actually somewhat off center. I think (but admittedly can't prove) that what's happening is that the icon's edge is centered (rather than the center of the icon being centered), which gives the icon an "off-center" look. I'd like to be able to center the center of the icon, but all the references I've found so far are how to center the whole icon (which is what I'm already doing).

One thing I thought of doing is calculating the absolute (or relative) position somewhere in code, but I would strongly prefer not to do that if I can avoid it because this seems like a "fragile" and labor-intensive way of doing it.

My template is as follows:

<div
    class="rectangle"
    (click)="clicked(item)"
    [style.backgroundColor]="item.color"
    *ngIf="item.itemType == allEnumTypes.ClickButton"
    title="{{ item.warning }}"
  >
    <mat-icon
      *ngIf="item.icon"
      fontIcon="{{ item.icon }}"
      [style.color]="item.iconColor"
      class="large-icon"
      style="padding-top: 20%; padding-right: 30%"
    ></mat-icon><br /><br />
    <span class="select-button-text" [style.color]="item.fontColor" style="padding-bottom: 0%">{{ item.display }}</span>
  </div>

The CSS for the rectangle class is:

.rectangle {
  width: 139px;
  height: 125px;
  border: 2px solid #bfc0c2;
  opacity: 1;
  text-align: center !important;
  background: #ffffff 0% 0% no-repeat padding-box;
}

Can someone point out my mistake here?

CodePudding user response:

I like use css-flex to center

  .center{
    display:flex;
    flex-direction:column;
    justify-content:center;
    align-items:center;
  }

If you rectangle is

.rectangle {
    width: 139px;
    height: 125px;
    border: 2px solid #bfc0c2;
  }

You can do

<div class="center rectangle">
  <!--see that the margin-top is equal to the line-height-->
  <div class="center" style="margin-top:1.25rem">
    <mat-icon
      aria-hidden="false"
      style="font-size: 3rem;width:3rem;height:3rem"
      aria-label="Example home icon"
      >home</mat-icon
    >
    <div style="line-height: 1.25rem">Home</div>
  </div>
</div>

or if you want to center the group icon and label

<div class="center rectangle">
    <mat-icon
      aria-hidden="false"
      style="font-size: 3rem;width:3rem;height:3rem"
      aria-label="Example home icon"
      >home</mat-icon
    >
    <div style="line-height: 1.25rem">Home</div>
</div>

See the stackblitz

NOTE: See that to change the size of a mat-icon you should change the font-size, the width and the height

  • Related