Dhana D.
Dhana D.

Reputation: 1720

How to make a div scroll to stick inside a div and under another div?

I tried to create a webpage that won't scroll the entire page, but just scroll in the card, in the snippet below, just assume that the teal box is the card. I want the sticky to stick under the h2 and also make h2 position fixed, not to the topmost of the page.

The sticky works normally when top: 0.

div.article {
  background: #ccffee;
  padding: 30px;
}
div.sticky {
  position: -webkit-sticky;
  position: sticky;
  top: 0;
  padding: 50px;
  font-size: 20px;
  background-color: yellow;
}

div.two {
  background-color: #e8e8e8;
}

.content {
  height: 500px;
  background: #ffc0cb;
}
<h1>Web Title</h1>
<div class="article">
<h2>Title</h2>
<div class="sticky one">Sticky Stack 1</div>
<div class="sticky two">Sticky Stack 2</div>

<div class="content">Some example text..</div>
</div>

But it doesn't work when I assign top to more than 0.

div.article {
  background: #ccffee;
  padding: 30px;
}
div.sticky {
  position: -webkit-sticky;
  position: sticky;
  top: 30;
  padding: 50px;
  font-size: 20px;
  background-color: yellow;
}

div.two {
  background-color: #e8e8e8;
}

.content {
  height: 500px;
  background: #ffc0cb;
}
<h1>Web Title</h1>
<div class="article">
<h2>Title</h2>
<div class="sticky one">Sticky Stack 1</div>
<div class="sticky two">Sticky Stack 2</div>

<div class="content">Some example text..</div>
</div>

What's actually wrong on this sticky and how can I resolve this to get the desired appearance? Is it also possible for me to make the two just fully appear when the scrolling point just get there, I mean, the div.one will not have any scroll animation/cropped by the boundaries, when the user scroll down 3 times, it will just get the two appears in a blink and the one already placed at the top/disappeared and that also for scroll up?

Upvotes: 0

Views: 876

Answers (1)

dave
dave

Reputation: 2901

You need to add px to the end of your top value:

top:30px;;

div.article {
  background: #ccffee;
  padding: 30px;
}

div.sticky {
  position: -webkit-sticky;
  position: sticky;
  top: 50px;
  padding: 50px;
  font-size: 20px;
  background-color: yellow;
}

div.two {
  background-color: #e8e8e8;
}

.content {
  height: 500px;
  background: #ffc0cb;
}

.heading {
  top:10px;
  position:sticky;
}
<h1>Web Title</h1>
<div class="article">
  <div class="heading"><h2>Title</h2></div>
  <div class="sticky one">Sticky Stack 1</div>
  <div class="sticky two">Sticky Stack 2</div>
  <div class="content">Some example text..</div>
</div>

Upvotes: 1

Related Questions