Search code examples
jqueryhtmlcsssticky

Create a sticky element


I would like to create a sticky element on this JSFIDDLE. The 'blue' div should be fixed until the 'pink' touch it and then the 'blue' div could be in relative position.

HTML :

<div class='blue'> I want to stay 'fixe' until the pink bloc touch me. </br> Then I can be 'relative'.</div>

<div class='pink'></div>

CSS :

body {margin:0;}

.blue {
 height:50vh;
 position:relative;
 width:100%;
 display:inline-block;
 background:blue;
 color:white;
 text-align:center;
}

.pink {
 height:500vh;
 margin-top:40vh;
 position:absolute;
 width:100%;
 display:inline-block;
 background:pink;
}

Solution

  • You can do it using sticky position. Simply pay attention to browser support

    body {
      margin: 0;
    }
    
    .container {
      height: 90vh; /*height of the blue + margin-top of the pink*/
    }
    
    .blue {
      height: 50vh;
      position: sticky;
      top: 0;
      background: blue;
      color: white;
      text-align: center;
    }
    
    .pink {
      height: 500vh;
      background: pink;
    }
    <div class="container">
      <div class='blue'> I want to stay 'fixe' until the pink bloc touch me. <br> Then I can be 'relative'.</div>
    </div>
    <div class='pink'></div>