Ionic 2 responsive grid

2020-03-09 08:34发布

问题:

How can I make a responsive grid in Ionic 2? Ionic 1 supported reserved classes like responsive-md or responsive-sm that made grids responsive, but they don't seem to work in Ionic 2.

In my case I have an <ion-row> with three <ion-col>. I would like the columns to drop below each other when the display width drops below a threshold. Is it possible to do this with Ionic 2?

回答1:

Though it does not seem to appear in the Ionic 2 documentation currently, the responsive-md, responsive-sm (etc.) classes in Ionic 1 now become individual attributes in Ionic 2.

Here is an example:

  <ion-row responsive-sm>
    <ion-col width-10>This column will take 10% of space</ion-col>
  </ion-row>


回答2:

Now Ionic is using Bootstrap grid system. We can also use fixed attribute on ion-grid to better utilize screen width.

I tried by using following code for my requirements. Please follow the comments for understanding.

We can override the breakpoints so I did this:

$grid-breakpoints: (
  sm: 0,
  ssm: 320px, // second small breakpoint
  tsm: 372px, // third small breakpoint. This is the threshold for high resolution devices. 
  md: 768px,
  lg: 1024px
);

$grid-max-widths: (
  sm: 292px,
  ssm: 100%,
  tsm: 100%,
  md: 720px,
  lg: 960px
);  

and here is the code using customised breakpoint:

 <ion-grid fixed>
      <ion-row>
        <ion-col col-2 col-tsm-2>
          1 of 3
        </ion-col>
        <ion-col col-10 col-tsm-6>
          2 of 3
        </ion-col>
        <ion-col col-4 push-2 push-tsm-0 col-tsm-4> // pushing 2 columns at the beginning for low resolution devices
          3 of 3
        </ion-col>
      </ion-row>
    </ion-grid>

You would get following output for low resolution devices i.e devices that are below min-width: 372px;

And following output for above devices:



回答3:

Update for Ionic 2, Ionic 3+:

Ionic now have an amazing grid system base on flexbox css. You can see in the docs.
To use it, just simple like that:

<ion-grid>
  <ion-row>
    <ion-col col-3></ion-col> //This col will take 3/12 = 25% width;
    <ion-col col-4></ion-col> //This col will take 4/12 = 33.33% width;
    <ion-col></ion-col>       //This col will take the rest of width;
  </ion-row>
</ion-grid>