I have 3 elements : 1 toolbar, 1 map , an other toolbar. the elements are one below the other
I want that the second toolbar stay under the map element (at 400px of the top) but when i scroll down, my second toolbar will stop at 50px of the top and will fix under the first.
Thanks for your help
//Component.html
<mat-toolbar color="primary" [ngStyle]="{'height':'50px'}" class="fixed-header" >
</mat-toolbar>
<div class="custom-popup" id="frugalmap" ></div>
<mat-toolbar color="warn" class="mat-elevation-z5">
</mat-toolbar>
//Component.css
.fixed-header {
position: fixed;
z-index:999;
}
#frugalmap {
height: 300px;
width: 100%;
margin-top:50px;
}
.mat-elevation-z5 {
position: relative;
z-index: 2;
}
Before I answer your question, you may consider:
z-index: 100000000
.!important
only when there's no other choice.Since we can't write Angular code via StackOverflow's snippets, I wrote the code using Stackblitz - https://stackblitz.com/edit/angular-ii5tnn
To make a position sticky, well, you simply use position: sticky
, with additional top
or bottom
rule (in this case - top). For example:
mat-toolbar {
position: sticky;
top: 50px
}
This way, mat-toolbar
will remain at his position, until we pass it.
In my given example, I did:
mat-toolbar
with [color="primary"]
and set it to fixed via CSS.#frugelmap
with custom height just to show it.mat-toolbar
with [color="warn"]
and set the sticky rules (watch below)#add-spacing
with lots of lorem ipsum just do demonstrate the sticky effect.The following CSS rules:
mat-toolbar {
--default-height: 50px;
}
mat-toolbar[color="primary"] {
top: 0;
position: fixed;
height: var(--default-height);
}
mat-toolbar[color="warn"] {
position: sticky;
top: var(--default-height);
}
#frugalmap {
height: 300px;
background-color: #EEE;
}
To avoid the browser support concerns of position: sticky
, you can easily achieve this by using ngClass
to toggle sticky behaviour as:
component.html
<mat-toolbar color="primary" class="fixed-header" >
</mat-toolbar>
<div class="custom-popup" id="frugalmap" ></div>
<mat-toolbar
id="secondToolbar" color="warn"
[ngClass]="{'mat-elevation-z5' : true, 'sticky' : isSticky}">
</mat-toolbar>
usign HostListener
to track scroll position as you should not use JS event handler directly in Angular:
component.ts
isSticky: boolean = false;
@HostListener('window:scroll', ['$event'])
checkScroll() {
this.isSticky = window.pageYOffset >= 250;
}
finally adding style for our custom class sticky
.
component.css
.fixed-header {
position: fixed;
z-index:999;
height: 50px;
}
#frugalmap {
height: 300px;
width: 100%;
top: 50px;
position: relative;
}
.mat-elevation-z5 {
position: relative;
}
.sticky {
position: fixed;
top: 50px;
}
Stackblitz Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With