Ioan Moldovan
Ioan Moldovan

Reputation: 2412

How to put image in both <ion-header> and <ion-content> in Ionic

I'm currently developing Ionic app and stuck at implementing image in both ion-header and ion-content.

Here's screenshot how I implemented. As you can see from screenshot, ion header and ion-content contents are hidden because I set image z-index to high number;

enter image description here

Could anyone please suggest how to achieve this? Thanks.

Upvotes: 4

Views: 2275

Answers (1)

sebaferreras
sebaferreras

Reputation: 44659

There's an easier way to do that, and it's by using the fullscreen property from the ion-content component (docs). So the trick is to make the content to be fullscreen and then to set the background of the header to be transparent so that it doesn't cover the background.

Template:

<ion-header class="ion-no-border">
  <ion-toolbar>
    <ion-title>Home</ion-title>
  </ion-toolbar>
</ion-header>

<ion-content class="ion-padding" fullscreen>
  ...
  ...
</ion-content>

Styles:

ion-toolbar {
  --ion-toolbar-background: transparent;
}

ion-content {
  --background: url('/assets/your_image.jpg') no-repeat center center / cover;
}

Important: There's currently an issue that makes the backgroung image to flicker in some specific scenarios (Github issue). If this issue affects your app, the recommended workaround is to set the background in the component instead of by using css like this:

Template:

<ion-header class="ion-no-border">
  <ion-toolbar>
    <ion-title>Home</ion-title>
  </ion-toolbar>
</ion-header>

<!-- The only change is the id added to the ion-content -->
<ion-content id="my-page-content" class="ion-padding" fullscreen>
  ...
  ...
</ion-content>

Styles:

ion-toolbar {
  --ion-toolbar-background: transparent;
}

ion-content {
  // Do not set the background here!
}

Component:

import { DomController } from '@ionic/angular';

// ...

@Component({...})
export class MyPage { 

  constructor(private domController: DomController) {}

  // ...

  ionViewWillEnter() {
    this.initializeBackground();
  }

  // ...

  private initializeBackground(): void {
    try {
      const content = document.querySelector('#my-page-content');
      const innerScroll = content.shadowRoot.querySelector('.inner-scroll');

      this.domController.write(() => {
        innerScroll.setAttribute(
          'style',
          'background: url("/assets/img/your_image.jpg") no-repeat center center / cover',
        );
      });
    } catch (e) {}
  }
}

Upvotes: 2

Related Questions