Home > front end >  How to I position something sticky so that it follows the screen in the center vertically
How to I position something sticky so that it follows the screen in the center vertically

Time:07-18

As you can see in my snippet I have almost acheived my desired effect, by using top: 50%;. But is not exactly centered on the screen. If I add transform: translateY(-50%); I do acheive centering, however now the red div is position too far up initially and doesnt go all the way to the bottom. Anyone got any ideas?

(also please note that I cant know the height of this red div because it is supposed to be an image first of all, and second I need it to be responsive meaning the height will change)

* {
  margin: 0;
  padding: 0;
}
.other_content {
  height: 80vh;
  width: 100%;
  background-color: #eee;
}
section {
  background-color: skyblue;
  height: 300vh;
  width: 100%;
  position: relative;
}

.sticky {
  position: sticky;
  top: 50%;
  /* transform: translateY(-50%); *//* DOES NOT WORK */
  width: 90%;
  margin-left: 5%;
  background-color: red;
}
<div ></div>
<section>
  <div >
    <p>IMAGE WITH <br> UNKNOWN <br> HEIGHT <br> GOES HERE</p>
  </div>
</section>
<div ></div>

CodePudding user response:

.sticky {
  position: sticky;
  top: 45%
  /* transform: translateY(-50%); *//* DOES NOT WORK */
  width: 90%;
  margin-left: 5%;
  background-color: red;
}

Just change the top percentage from 50% to 45%;

CodePudding user response:

If I understand your question correctly, can you change the top to 40% to make it higher? 45% (should) perfectly align it in the middle.

* {
  margin: 0;
  padding: 0;
}
.other_content {
  height: 80vh;
  width: 100%;
  background-color: #eee;
}
section {
  background-color: skyblue;
  height: 300vh;
  width: 100%;
  position: relative;
}
.sticky {
  position: sticky;
  top: 45%;
  /* transform: translateY(-50%); *//* DOES NOT WORK */
  width: 90%;
  margin-left: 5%;
  background-color: red;
}
<div ></div>
<section>
  <div >
    <p>IMAGE WITH <br> UNKNOWN <br> HEIGHT <br> GOES HERE</p>
  </div>
</section>
<div ></div>

  • Related