Centering content

OK, so you’re primarily concerned about a single axis. I consider myself very weak at CSS, so this may be very unidiomatic or suboptimal, but these “security blanket” classes have stayed with me for years now:

.fullheight {
  height: 100%;
}

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

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

.hcs {
  display: flex;
  flex-direction: row;
  align-items: center;
}

fullheight is pretty self-explanatory. vcs means “vertical list of centered stuff”, and hcs is correspondingly “horizontal list of centered stuff”. They are designed to have multiple children, and center them on a single axis. xc is a visual metaphor for centering a single child right in the cross of an “x”.

I figure “Ionic gonna Ionic” when it comes to top-level elements like <ion-header> or <ion-content>, so I just leave them be and work one level inside them. So what I think you’re asking for, if you throw those classes into global.scss, would be something like this:

<ion-content>
    <div class="vcs">
      <div>we only care</div>
      <div>about side to side</div>
    </div>
</ion-content>

If by “center” you had meant both horizontal and vertical, we could do:

<ion-content>
    <div class="fullheight xc">
        <div class="vcs">
            <div>now we control the horizontal</div>
            <div>and the vertical</div>
        </div>
    </div>
</ion-content>

Hopefully you can adapt this to your needs.

2 Likes