简体   繁体   中英

How to Make a sticky element 'float'

I ran into a weird layout issue and couldn't think of a way to figure that out. The title might be a little confusing but let me show the code.

 #root-container { display: flex; } #container1 { width: 100px; height: 500px; background-color: grey; } #sticky-container { width: 320px; max-height: 500px; position: relative; background-color: lightgrey; } #sticky-container-header { width: 320px; height: 100px; background-color: #2f4d92; } #full-height-content { width: 100%; height: 400px; overflow-y: scroll; background-color: #d67e23; } #sticky-content { width: 80%; height: 100px; position: sticky; bottom: 20px; background-color: rgba(0,0,0,0.5); } #bottom { width: 420px; height: 100px; background-color: purple; }
 <div id='root-container'> <div id="container1"></div> <div id="sticky-container"> <div id='sticky-container-header'></div> <div id='full-height-content'> Saw yet kindness too replying whatever marianne. Old sentiments resolution admiration unaffected its mrs literature. Behaviour new set existence dashwoods. It satisfied to mr commanded consisted disposing engrossed. Tall snug do of till on easy. Form not calm new fail. His followed carriage proposal entrance directly had elegance. Greater for cottage gay parties natural. Remaining he furniture on he discourse suspected perpetual. Power dried her taken place day ought the. Four and our ham west miss. Education shameless who middleton agreement how. We in found world chief is at means weeks smile. Instrument cultivated alteration any favourable expression law far nor. Both new like tore but year. An from mean on with when sing pain. Oh to as principles devonshire companions unsatiable an delightful. The ourselves suffering the sincerity. Inhabit her manners adapted age certain. Debating offended at branched striking be subjects. Must you with him from him her were more. In eldest be it result should remark vanity square. Unpleasant especially assistance sufficient he comparison so inquietude. Branch one shy edward stairs turned has law wonder horses. Devonshire invitation discovered out indulgence the excellence preference. Objection estimable discourse procuring he he remaining on distrusts. Simplicity affronting inquietude for now sympathize age. She meant new their sex could defer child. An lose at quit to life do dull. Surrounded affronting favourable no mr. Lain knew like half she yet joy. Be than dull as seen very shot. Attachment ye so am travelling estimating projecting is. Off fat address attacks his besides. Suitable settling mr attended no doubtful feelings. Any over for say bore such sold five but hung. Lose john poor same it case do year we. Full how way even the sigh. Extremely nor furniture fat questions now provision incommode preserved. Our side fail find like now. Discovered travelling for insensible partiality unpleasing impossible she. Sudden up my excuse to suffer ladies though or. Bachelor possible marianne directly confined relation as on he. Unpacked reserved sir offering bed judgment may and quitting speaking. Is do be improved raptures offering required in replying raillery. Stairs ladies friend by in mutual an no. Mr hence chief he cause. Whole no doors on hoped. Mile tell if help they ye full name. Cultivated who resolution connection motionless did occasional. Journey promise if it colonel. Can all mirth abode nor hills added. Them men does for body pure. Far end not horses remain sister. Mr parish is to he answer roused piqued afford sussex. It abode words began enjoy years no do no. Tried spoil as heart visit blush or. Boy possible blessing sensible set but margaret interest. Off tears are day blind smile alone had. Spot of come to ever hand as lady meet on. Delicate contempt received two yet advanced. Gentleman as belonging he commanded believing dejection in by. On no am winding chicken so behaved. Its preserved sex enjoyment new way behaviour. Him yet devonshire celebrated especially. Unfeeling one provision are smallness resembled repulsive. Entire any had depend and figure winter. Change stairs and men likely wisdom new </div> <div id='sticky-content'></div> </div> </div> <div id="bottom"> </div>

Suppose the viewport is not tall enough and we need to scroll all the way to the bottom to see the purple block (the bottom div).

What I want is:

  1. when we scroll from top to bottom and the purple block hasn't shown up yet, the transparent block is sticky to 20px above the bottom of the orange block. Which has been done with position: sticky .

  2. when the purple block starts to show up, stop the transparent block from moving down and keep it at the position where it's 20px above the bottom of the orange block as if it's a floating button. This fails since a sticky element is positioned according to the normal flow of the document . So in this case, when purple block completely shows up, the transparent block is 20px below the bottom of the orange block.

I wonder if there are any ways to realize both. It would be good if we could realize this with just css. But simple JS code is also preferred. Thanks!

One idea is to move the sticky element to the top of the container instead of the bottom and rely on negative margin to avoid the normal flow behavior when it's on the top then it will stop when reaching the bottom edge of the container.

Check the comment below to better understand. The only drawback is that some value need to be set manually based on the height of the element. You will also note the value of the top that also need to be set manually depending the screen size to simulate the bottom stick behavior.

 #root-container { display: flex; } #container1 { width: 100px; height: 500px; background-color: grey; } #sticky-container { width: 320px; max-height: 500px; position: relative; background-color: lightgrey; } #sticky-container-header { width: 320px; height: 100px; background-color: #2f4d92; } #full-height-content { width: 100%; height: 400px; overflow-y: scroll; background-color: #d67e23; margin-top:-20px; /*same as the margin-bottom*/ } #sticky-content { width: 80%; height: 100px; margin-top:-100px; /*same as height*/ margin-bottom:20px; /*to avoid going under the bottom:20px we want*/ position: sticky; top:calc(100vh - 100px - 20px); background-color: rgba(0,0,0,0.5); } #bottom { width: 420px; height: 100px; background-color: purple; } body { margin:0; } 
 <div id='root-container'> <div id="container1"></div> <div id="sticky-container"> <div id='sticky-container-header'></div> <div id='sticky-content'></div> <div id='full-height-content'> Saw yet kindness too replying whatever marianne. Old sentiments resolution admiration unaffected its mrs literature. Behaviour new set existence dashwoods. It satisfied to mr commanded consisted disposing engrossed. Tall snug do of till on easy. Form not calm new fail. His followed carriage proposal entrance directly had elegance. Greater for cottage gay parties natural. Remaining he furniture on he discourse suspected perpetual. Power dried her taken place day ought the. Four and our ham west miss. Education shameless who middleton agreement how. We in found world chief is at means weeks smile. Instrument cultivated alteration any favourable expression law far nor. Both new like tore but year. An from mean on with when sing pain. Oh to as principles devonshire companions unsatiable an delightful. The ourselves suffering the sincerity. Inhabit her manners adapted age certain. Debating offended at branched striking be subjects. Must you with him from him her were more. In eldest be it result should remark vanity square. Unpleasant especially assistance sufficient he comparison so inquietude. Branch one shy edward stairs turned has law wonder horses. Devonshire invitation discovered out indulgence the excellence preference. Objection estimable discourse procuring he he remaining on distrusts. Simplicity affronting inquietude for now sympathize age. She meant new their sex could defer child. An lose at quit to life do dull. Surrounded affronting favourable no mr. Lain knew like half she yet joy. Be than dull as seen very shot. Attachment ye so am travelling estimating projecting is. Off fat address attacks his besides. Suitable settling mr attended no doubtful feelings. Any over for say bore such sold five but hung. Lose john poor same it case do year we. Full how way even the sigh. Extremely nor furniture fat questions now provision incommode preserved. Our side fail find like now. Discovered travelling for insensible partiality unpleasing impossible she. Sudden up my excuse to suffer ladies though or. Bachelor possible marianne directly confined relation as on he. Unpacked reserved sir offering bed judgment may and quitting speaking. Is do be improved raptures offering required in replying raillery. Stairs ladies friend by in mutual an no. Mr hence chief he cause. Whole no doors on hoped. Mile tell if help they ye full name. Cultivated who resolution connection motionless did occasional. Journey promise if it colonel. Can all mirth abode nor hills added. Them men does for body pure. Far end not horses remain sister. Mr parish is to he answer roused piqued afford sussex. It abode words began enjoy years no do no. Tried spoil as heart visit blush or. Boy possible blessing sensible set but margaret interest. Off tears are day blind smile alone had. Spot of come to ever hand as lady meet on. Delicate contempt received two yet advanced. Gentleman as belonging he commanded believing dejection in by. On no am winding chicken so behaved. Its preserved sex enjoyment new way behaviour. Him yet devonshire celebrated especially. Unfeeling one provision are smallness resembled repulsive. Entire any had depend and figure winter. Change stairs and men likely wisdom new </div> </div> </div> <div id="bottom"> </div> 

Why this won't work with CSS

If you wish to avoid negative margins or are dealing with variable heights then this won't work with CSS. Your relative container #sticky-container has content #full-height-content with 400px height. Position sticky cannot work both ways. You can either position this to its scrolling ancestor (the document) or by setting an overflow property on #sticky-container you could position it there.

The element is positioned according to the normal flow of the document, and then offset relative to its nearest scrolling ancestor and containing block (nearest block-level ancestor)

If you set an overflow property (say overflow-y: hidden ) on #sticky-container then your #sticky-content element would potentially be 400px down in the document, and not 20px from the bottom of the viewport (which is what you want).

You seem to want the sticky element to stick to the viewport and then in a way "stick" absolutely to the #sticky-container element when #bottom becomes visible.

How JavaScript can solve this

By using JavaScript and an IntersectionObserver you can have it both ways. #sticky-content will behave as you have it, until #bottom enters the viewport. Once it does, we add a class ( .is-absolute ) to #sticky-content which positions it absolute rather than sticky and then it will be 20px from the bottom of its relative parent #sticky-container (and no longer to its scrolling ancestor, the viewport). The IntersectionObserver will handle the inverse of removing this class when #bottom leaves the viewport.

Take note: IntersectionObserver is fairly new and not yet broadly supported by all major browsers. You may have some luck with a polyfill .

 // The elements we want to control var stickyContent = document.querySelector('#sticky-content'); var stickyContentActiveClass = 'is-absolute'; var bottom = document.querySelector('#bottom'); // The function to call when #bottom intersects with the viewport var callback = function(entries, observer) { entries.forEach(entry => { if (entry.isIntersecting) { stickyContent.classList.add(stickyContentActiveClass); } else { stickyContent.classList.remove(stickyContentActiveClass); } }); }; // Setting up the observer with an argument of 0 for the threshold // Our callback function will run as soon as #bottom enters the viewport var observer = new IntersectionObserver(callback, {threshold: 0}); // Tell our observer to watch #bottom observer.observe(bottom); 
 #root-container { display: flex; } #container1 { width: 100px; height: 500px; background-color: grey; } #sticky-container { width: 320px; max-height: 500px; position: relative; background-color: lightgrey; } #sticky-container-header { width: 320px; height: 100px; background-color: #2f4d92; } #full-height-content { width: 100%; height: 400px; overflow-y: scroll; background-color: #d67e23; } #sticky-content { width: 80%; height: 100px; position: sticky; bottom: 20px; background-color: rgba(0,0,0,0.5); } #sticky-content.is-absolute { position: absolute; } #bottom { width: 420px; height: 100px; background-color: purple; } 
 <div id='root-container'> <div id="container1"></div> <div id="sticky-container"> <div id='sticky-container-header'></div> <div id='full-height-content'> Saw yet kindness too replying whatever marianne. Old sentiments resolution admiration unaffected its mrs literature. Behaviour new set existence dashwoods. It satisfied to mr commanded consisted disposing engrossed. Tall snug do of till on easy. Form not calm new fail. His followed carriage proposal entrance directly had elegance. Greater for cottage gay parties natural. Remaining he furniture on he discourse suspected perpetual. Power dried her taken place day ought the. Four and our ham west miss. Education shameless who middleton agreement how. We in found world chief is at means weeks smile. Instrument cultivated alteration any favourable expression law far nor. Both new like tore but year. An from mean on with when sing pain. Oh to as principles devonshire companions unsatiable an delightful. The ourselves suffering the sincerity. Inhabit her manners adapted age certain. Debating offended at branched striking be subjects. Must you with him from him her were more. In eldest be it result should remark vanity square. Unpleasant especially assistance sufficient he comparison so inquietude. Branch one shy edward stairs turned has law wonder horses. Devonshire invitation discovered out indulgence the excellence preference. Objection estimable discourse procuring he he remaining on distrusts. Simplicity affronting inquietude for now sympathize age. She meant new their sex could defer child. An lose at quit to life do dull. Surrounded affronting favourable no mr. Lain knew like half she yet joy. Be than dull as seen very shot. Attachment ye so am travelling estimating projecting is. Off fat address attacks his besides. Suitable settling mr attended no doubtful feelings. Any over for say bore such sold five but hung. Lose john poor same it case do year we. Full how way even the sigh. Extremely nor furniture fat questions now provision incommode preserved. Our side fail find like now. Discovered travelling for insensible partiality unpleasing impossible she. Sudden up my excuse to suffer ladies though or. Bachelor possible marianne directly confined relation as on he. Unpacked reserved sir offering bed judgment may and quitting speaking. Is do be improved raptures offering required in replying raillery. Stairs ladies friend by in mutual an no. Mr hence chief he cause. Whole no doors on hoped. Mile tell if help they ye full name. Cultivated who resolution connection motionless did occasional. Journey promise if it colonel. Can all mirth abode nor hills added. Them men does for body pure. Far end not horses remain sister. Mr parish is to he answer roused piqued afford sussex. It abode words began enjoy years no do no. Tried spoil as heart visit blush or. Boy possible blessing sensible set but margaret interest. Off tears are day blind smile alone had. Spot of come to ever hand as lady meet on. Delicate contempt received two yet advanced. Gentleman as belonging he commanded believing dejection in by. On no am winding chicken so behaved. Its preserved sex enjoyment new way behaviour. Him yet devonshire celebrated especially. Unfeeling one provision are smallness resembled repulsive. Entire any had depend and figure winter. Change stairs and men likely wisdom new </div> <div id='sticky-content'></div> </div> </div> <div id="bottom"> </div> 

I tried to solve this issue with a simple css sticky position

button<div class="root">
    <div class='header'></div>
    <div class='content'>
      Saw yet kindness too replying whatever marianne. Old sentiments resolution admiration unaffected its mrs literature. Behaviour new set existence dashwoods. It satisfied to mr commanded consisted disposing engrossed. Tall snug do of till on easy. Form not calm new fail.

      His followed carriage proposal entrance directly had elegance. Greater for cottage gay parties natural. Remaining he furniture on he discourse suspected perpetual. Power dried her taken place day ought the. Four and our ham west miss. Education shameless who middleton agreement how. We in found world chief is at means weeks smile.

      Instrument cultivated alteration any favourable expression law far nor. Both new like tore but year. An from mean on with when sing pain. Oh to as principles devonshire companions unsatiable an delightful. The ourselves suffering the sincerity. Inhabit her manners adapted age certain. Debating offended at branched striking be subjects.

      Must you with him from him her were more. In eldest be it result should remark vanity square. Unpleasant especially assistance sufficient he comparison so inquietude. Branch one shy edward stairs turned has law wonder horses. Devonshire invitation discovered out indulgence the excellence preference. Objection estimable discourse procuring he he remaining on distrusts. Simplicity affronting inquietude for now sympathize age. She meant new their sex could defer child. An lose at quit to life do dull.

      Surrounded affronting favourable no mr. Lain knew like half she yet joy. Be than dull as seen very shot. Attachment ye so am travelling estimating projecting is. Off fat address attacks his besides. Suitable settling mr attended no doubtful feelings. Any over for say bore such sold five but hung.
      Lose john poor same it case do year we. Full how way even the sigh. Extremely nor furniture fat questions now provision incommode preserved. Our side fail find like now. Discovered travelling for insensible partiality unpleasing impossible she. Sudden up my excuse to suffer ladies though or. Bachelor possible marianne directly confined relation as on he.

      Unpacked reserved sir offering bed judgment may and quitting speaking. Is do be improved raptures offering required in replying raillery. Stairs ladies friend by in mutual an no. Mr hence chief he cause. Whole no doors on hoped. Mile tell if help they ye full name.

      Cultivated who resolution connection motionless did occasional. Journey promise if it colonel. Can all mirth abode nor hills added. Them men does for body pure. Far end not horses remain sister. Mr parish is to he answer roused piqued afford sussex. It abode words began enjoy years no do no. Tried spoil as heart visit blush or. Boy possible blessing sensible set but margaret interest. Off tears are day blind smile alone had.

      Spot of come to ever hand as lady meet on. Delicate contempt received two yet advanced. Gentleman as belonging he commanded believing dejection in by. On no am winding chicken so behaved. Its preserved sex enjoyment new way behaviour. Him yet devonshire celebrated especially. Unfeeling one provision are smallness resembled repulsive.

      Entire any had depend and figure winter. Change stairs and men likely wisdom new
    </div>
    <div class='sticky-container'>
       <div class='button'></div>
    </div>
  <div class="footer"></div>
</div>
.root {
  width: 320px;
  margin: 0 auto;
}

.header {
  height: 200px;
  background-color: #2f4d92;
}

.content {
  background-color: #d67e23;
  margin-top:
}

.sticky-container {
  height: 0;
  width: 0;
  overflow: visible;
  position: sticky;
  margin-left: auto;
  bottom: 0;
  background-color: rgba(0,0,0,0.5);
}

.button {
  width: 40px;
  height: 40px;
  border-radius: 100%;
  bottom: 0;
  background-color: red;
  transform: translate(-100%, -100%);
}

.footer {
  height: 300px;
  background-color: purple;
}

here is the codepen

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM