Home > Net >  Position relative to the visible part of its container
Position relative to the visible part of its container

Time:07-25

So in the example below, I would like the label to always be visible at the top of the visible red part even if we scroll vertically. Is this possible to do in css?

.my_label {
 color:white
}
.event{
  height:200px;
  background-color:red
}
 1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>
    2<br>2<br>2<br>2<br>2<br>2<br>2<br>2<br>2<br>2<br>2<br>2<br>
<div >
    <div >My Label</div>
    </div>
    1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>
    2<br>2<br>2<br>2<br>2<br>2<br>2<br>2<br>2<br>2<br>2<br>2<br>
    3<br>3<br>3<br>3<br>3<br>3<br>3<br>3<br>3<br>3<br>3<br>3<br>
    4<br>4<br>4<br>4<br>4<br>4<br>4<br>4<br>4<br>4<br>4<br>4<br>
  

CodePudding user response:

You can use position: sticky

You can read more about it here but basically it will act as position relative until you scroll to it then it will act as position fixed and stick to the position you set it to until you scroll out of it

In this example I set it to stick to top of the screen by giving it top: 0

.h-50{
  height: 50vh;
}
.h-100{
  height: 100vh;
}

.bg-red{
  background-color: red;
}
.bg-green{
  background-color: green;
}
.bg-pink{
  background-color: pink;
}

.normal{
  position: relative;
}
.sticky {
  position: sticky;
  top:0;
}
<div >This will not stick</div>
<div >This will stick</div>
<div >This will not stick</div>

  • Related