Ionic 4 - Header background image

I want to set an image as background of an ion-header/ion-toolbar.

For Ionic version 3 this solution worked very well: How to set background image for header?
It just used the class “toolbar-background” for this purpose. This class also exists in Ionic 4.
But in ionic 4 it seems, that the css of the pages is only applied to the elements in ion-content, so it won’t change anything regarding the header. Even if I declare the necessary styles in the global.scss it is not applied to the header.

Edit: I need a solution to change the header per page. Pasting the css into the global.scss was just to verify that it works nowhere.

1 Like

In case someone encounters the same problem:

I found a somewhat hacky solution that works. The problem why whe can’t use css to style the header anymore is that ionic 4 encapsulates it inside a web component. Web components are meant to be uneffected by outside css.

Luckily we can absuse the color variables in “theme/variables.scss” to insert an image into the header. Because it’s content is direcly used as value for the css background property it is possible to do something like this:

--ion-color-medium: url("assets/custom-image.jpg") center / 100%;
<ion-header>
  <ion-toolbar color="medium">
    <ion-buttons slot="start">
      <ion-menu-button></ion-menu-button>
    </ion-buttons>
    <ion-title>
      Home
    </ion-title>
  </ion-toolbar>
</ion-header>
ion-header ion-toolbar {
  --background: url("assets/custom-image.jpg") center / 100%;
}

doesn’t work?

I also had to style the header of one single page indvdually and I did it like this:

:host { // this is the page itself
	background-color: green;

	ion-header ion-toolbar::shadow {
		--background: blue;
	}

	ion-content {
		--background: red;
	}
}

Found the solution here: https://www.html5rocks.com/en/tutorials/webcomponents/shadowdom-201/

For everyone who is still searching for a valid solution:
With this piece of code you can set a background image with a gradient overlay.

ion-toolbar {
    --background: linear-gradient(162deg, rgba(56, 70, 108, .8) 20%, rgba(56, 70, 108, .8) 100%), url('https://www.nexiga.com/geomarketing-blog/wp-content/uploads/2017/11/shutterstock_654668191_Parkhaus.jpg') bottom no-repeat;
}

Should look exactly like this:
Image not visible

2 Likes

If you want to use global.scss you have to put this:

ion-header {
    color: var(--ion-color-light) !important;
    ion-toolbar{
        --background: var(--ion-color-secondary) !important;
    }   
}

With the “important” stament to reset all others css

You can use like this…working good in my page

ion-content{
--background: #fff url('../../assets/imgs/intro.png') no-repeat center center / cover;
}

I hope it help you :slight_smile:

3 Likes

@ gokujy Great it works for me.