Richard
Richard

Reputation: 5091

Is it possible to mix absolute and sticky positioning?

In this example the inner grey div should be behaving like a sticky div - so it sticks to the top of the screen when you scroll down the page - but that ain't happening! What have I got wrong?

<div style="position: absolute; top: 150px; left: 150px; border: 1px solid red">
  <div style="position: sticky; top: 0; background-color: #ddd; padding: 20px; margin: 30px">
    Richard is the best
  </div>
</div>

<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>

Upvotes: 0

Views: 41

Answers (2)

Paulie_D
Paulie_D

Reputation: 114979

The outer div has only the sticky element as a child so it has nothing to scroll.

If you add the content inside the outer div it works fine.

div {
  background: linear-gradient(white, blue);
}

div div {
  background: grey;
}
<div style="position: absolute; top: 150px; left: 150px; border: 1px solid red">
  <div style="position: sticky; top: 0; padding: 20px; margin: 30px">
    Richard is the best
  </div>
  <p>&nbsp;</p>
  <p>&nbsp;</p>
  <p>&nbsp;</p>
  <p>&nbsp;</p>
  <p>&nbsp;</p>
  <p>&nbsp;</p>
  <p>&nbsp;</p>
  <p>&nbsp;</p>
  <p>&nbsp;</p>
  <p>&nbsp;</p>
  <p>&nbsp;</p>
  <p>&nbsp;</p>
  <p>&nbsp;</p>
  <p>&nbsp;</p>
  <p>&nbsp;</p>
  <p>&nbsp;</p>
  <p>&nbsp;</p>
  <p>&nbsp;</p>
  <p>&nbsp;</p>
  <p>&nbsp;</p>
  <p>&nbsp;</p>
  <p>&nbsp;</p>
  <p>&nbsp;</p>
  <p>&nbsp;</p>
</div>

Upvotes: 2

Symtox
Symtox

Reputation: 415

Look like you are trying to use position: fixed to me, maybe i didn't get your question right

<html>
    <body>
    
    <div style="position: fixed; top: 150px; left: 150px; border: 1px solid red">
        <div>
            Richard is the best
        </div>
    </div>
    
    <p>&nbsp;</p>
    <p>&nbsp;</p>
    <p>&nbsp;</p>
    <p>&nbsp;</p>
    <p>&nbsp;</p>
    <p>&nbsp;</p>
    <p>&nbsp;</p>
    <p>&nbsp;</p>
    <p>&nbsp;</p>
    <p>&nbsp;</p>
    <p>&nbsp;</p>
    <p>&nbsp;</p>
    <p>&nbsp;</p>
    <p>&nbsp;</p>
    <p>&nbsp;</p>
    <p>&nbsp;</p>
    <p>&nbsp;</p>
    <p>&nbsp;</p>
    <p>&nbsp;</p>
    <p>&nbsp;</p>
    <p>&nbsp;</p>
    <p>&nbsp;</p>
    <p>&nbsp;</p>
    <p>&nbsp;</p>
    
    </body>
    </html>

Upvotes: -1

Related Questions