Sammy Sammy - 5 months ago 33
CSS Question

Making nav bar slide into view from top

I currently have the following code in my angular app (2+):



.header {
background: rgba(white, 0);
&.fixed-top {
background: rgba(white, 1);
border-bottom: solid whitesmoke 1px;
position: fixed;
top: 0;
right: 0;
left: 0;
z-index: 1030;
}
}

<nav class="navbar navbar-toggleable-sm header" [class.fixed-top]="stickyHeader" (scroll)="scrollHandler()">...</nav>





The
handleScroll()
function simply sets
stickyHeader
to
true
after the user scrolls down "enough" pixels, and so the header menu becomes sticky. Here it is:



stickyHeader = false;

@HostListener('window:scroll', [])
scrollHandler() {
this.stickyHeader = window.scrollY > 90;
}





My question is: how can I make that menu appear to slide (animated) from top, as if it descended from above the browser?!

Answer Source

I am able to get the desired result by animating transform: translate using CSS animations

I have set animation-iteration-count to infinite for demo purposes. In your case it would be 1

To control the speed use animation-duration

I also use animation-fill-mode and set it to forwards to stop the animation at the end and not have it revert to the original state.

I added transform: translate(0, -20px) to .fixed-top to move it out of the display area until the animation starts.

Finally, I added animation-timing-function: ease; to control how the animation plays.

body {
  margin: 0 auto;
  padding: 0;
}

.fixed-top {
  background: red;
  z-index: 1030;
  width: 100%;
  height: 50%;
  animation-name: slide;
  animation-duration: 2s;
  animation-timing-function: ease;
  animation-iteration-count: infinite;
  animation-fill-mode: forwards;
  transform: translate(0, -20px)
}

@keyframes slide {
  0% {
    transform: translate(0, -20px);
    opacity:.1
  }
  100% {
    transform: translate(0, 0);
    opacity:1
  }
}
<div class="fixed-top">test</div>