Why centering children of “ion-content” doesn’t work but centering children of a “div” does?

Issue

I am trying to center children of ion-content using this HTML and SCSS codes:

<ion-header>
  <ion-toolbar color"primary">
    <ion-title>
      GreenWalls application
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content class"center">
  <ion-card>
    <ion-card-content>
      Awesome content
    </ion-card-content>
  </ion-card>
</ion-content>

ion-card {
  max-width: 350px;
}

.center {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
}

But this approach doesn’t result in centered content:

enter image description here

When I wrap the ion-card in div element and use the SCSS on the div element suddenly it works:

<ion-content>
  <div class"center">
    <ion-card>
      <ion-card-content>
        Awesome content
      </ion-card-content>
    </ion-card>
  </div>
</ion-content>

enter image description here

I don’t wanna wrap content of each ion-content in div tags. Why the SCSS doesn’t apply to the ion-content? How can I make it work in Ionic 4?

Solution

You may use <ion-grid> to wrap the children of <ion-content> instead of <div> element.

<ion-content>
  <ion-grid class"center">
    <ion-card>
      <ion-card-content>
        Awesome content
      </ion-card-content>
    </ion-card>
  </ion-grid>
</ion-content>

Sample Solution on StackBlitz


References

Center grid in ion-content

Answered By – Yong Shun

Leave a Comment