1

I want to make the image caption stick to the top of the viewport once a user scrolls the page, but it's not working. I would greatly appreciate the help, here is my HTML and CSS code:

 <div id="img-div">
      <img src="https://static.stacker.com/s3fs-public/styles/sar_screen_maximum_large/s3/Audrey%20Lead.png" id="image">
      <p id="img-caption"><strong>For beautiful eyes, look for the good in others; for beautiful lips, speak only words of kindness; and for poise, walk with the knowledge that you are never alone.<br><br>-Audrey Hepburn</strong></p>    
      </div>
html{
  width: 100vw;
}

body{
  width: 100%;
  margin: auto;
}

h1{
  position: absolute;
  z-index: 5;
}

#img-div{
  position: relative;
  height: 778px;
  width: 100%;
}

#image{
  background-repeat: no-repeat;
  height: 774px;
  width: 100%;
  object-fit: cover;
}


#img-caption{
  position: sticky;
  font-size: 19px;
  height: 9.5em;
  width: 21em;
  padding: 23px 13px 20px 23px;
  margin: 0;
  background-color: white;
  opacity: 70%;
  top: 0px;
  z-index: 5;
}
ATLA Fan
  • 29
  • 3

1 Answers1

1

The problem is that the stickiness position occurs in the given code in relation to the containing element, not in relation to the viewport.

This snippet takes the caption out of that element and then it sticks to the top of the viewport. (Note, to make things scrollable body has been given height 500vh for this demo).

html {
  width: 100vw;
}

body {
  width: 100%;
  margin: auto;
  height: 500vh;
}

h1 {
  position: absolute;
  z-index: 5;
}

#img-div {
  position: relative;
  height: 778px;
  width: 100%;
}

#image {
  background-repeat: no-repeat;
  height: 774px;
  width: 100%;
  object-fit: cover;
}

#img-caption {
  position: sticky;
  font-size: 19px;
  height: 9.5em;
  width: 21em;
  padding: 23px 13px 20px 23px;
  margin: 0;
  background-color: white;
  opacity: 70%;
  top: 0px;
  z-index: 5;
}
<div id="img-div">
  <img src="https://static.stacker.com/s3fs-public/styles/sar_screen_maximum_large/s3/Audrey%20Lead.png" id="image">
</div>
<p id="img-caption"><strong>For beautiful eyes, look for the good in others; for beautiful lips, speak only words of kindness; and for poise, walk with the knowledge that you are never alone.<br><br>-Audrey Hepburn</strong></p>
A Haworth
  • 30,908
  • 4
  • 11
  • 14