Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two divs to get fixed position, one after the other at the top

I have a fixed header and one hidden header which would display only after scrolling 100px from the top to the bottom.

The Fiddle here explains the layout:

.container {
  background: yellow;
}
.num1 {
  position: fixed;
  height: 25px;
  background: blue;
  text-align: center;
  width: 100%;
  top: 0;
}
.num2 {
  background: green;
  text-align: center;
  width: 280px;
  margin: 50px auto 0;
}

The blue div is fixed. The green div would be in hidden until the client scrolls it 100px of the page from top. After it crosses the 100px, it should start displaying and get position-fixed exactly next to the blue div.

How do I do that?

like image 395
stacky Avatar asked Sep 25 '22 17:09

stacky


2 Answers

DEMO

add jQuery code: in window.scroll event handler check the current scroll position (if over 100px show your second header, if less - move up away from the screen and hide);

$(window).scroll(function(){
  if ($(this).scrollTop()>100) { 
      $(".num2").css({"position":"fixed","top":25+"px","visibility":"visible"});  
  } else {
     $(".num2").css({"position":"absolute","top":-100+"px","visibility":"hidden"});  
  }
});
like image 152
GL.awog Avatar answered Sep 28 '22 06:09

GL.awog


I have just tried to build something.Let me now if it is exactly what you want.

Firstly you need to fix your html code because there are many tags that aren't closed:

<div class='container'>
    <div class='num1'>Hello Iam fixed</div>
    <div class='num2'>I would like to get fix while iam scrolling
    </div>
    <div class="content">Long text</div>
</div>

After you need to set up your css:

   body,html{
     paddin: 0;
     margin: 0;
   }  
   .container
   {
     background:yellow;
     width: 100%;
   }
   .num1
   {
      color: white;
      position: fixed;
      height:25px;
      background:blue;
      text-align: center;
      width:100%;
      top:0;
    }
    .num2
    {
      display: none;
      background:green;
      text-align:center;
      width:100%;
      height: 25px;
      position: fixed;
      top: 25px;
    }
    .content{
      margin-top: 25px;
      width: 100%;
    }

And at the end you need to use little of JavaScript.(I have used the library JQuery):

    $(function(){
    $(window).scroll(function(){
    var pxFromTop4 = $('.num1').offset().top;
    if(pxFromTop4 >= 100){
        $(".num2").fadeIn(300);
    }else{
        $(".num2").fadeOut(300);
    }
  });
});

And this is the link to JSFiddle:

Run the program

like image 43
Alex95 Avatar answered Sep 28 '22 05:09

Alex95