walacky
walacky

Reputation: 35

Css sticky position event

I'm using CSS position:sticky; to stick a div to bottom of the page.

Is that possible to change the width (or something else) of the div when the element is sticked?

Upvotes: 0

Views: 2483

Answers (3)

Yavanosta
Yavanosta

Reputation: 1670

I've made one more solution for this problem. It uses same idea as Eric Bidelman's but can cover some more corner cases.

You need to create some additional elements to track sticky header position. Eric calls them sentinel. In my solution they are thin 1px lines.

  1. Add one sentinel for each sticky side you want to observe. Set first sentinel top property equals to header top but with reverse sign minus

  2. For example if your header have top: 10px, then set sentinel header to -11px. You can use something like top: calc(-1px + -1 * var( — header-sticky-top)) or just set -1px if you have header top equals to zero.

  3. Add other sentinels if needed.
  4. Observe sentinels intersection with container using Intersection observer.
  5. You can say that header stuck if sentinel intersection record has isIntersecting = true, intersectionRatio = 0, and intersectionRect.top = rootBounds.top.
  6. Same other sides, just watch bottom, left, or right instead of top.
  7. Don’t forget to add visibility: hidden and pointer-events: none to sentinels.

You can find demo and source in this article: https://medium.com/@yavanosta/another-event-for-css-position-sticky-445a8d5663a

Upvotes: 0

Obsidian Age
Obsidian Age

Reputation: 42304

It's absolutely possible to apply width to an element with position: sticky.

Here's an example showcasing that:

body {
  height: 500px;
}

div.sticky {
  position: -webkit-sticky;
  position: sticky;
  top: 50px;
  padding: 5px;
  background-color: #cae8ca;
  border: 2px solid #4CAF50;
  width: 50px;
}
<div class="sticky">Sticky</div>

Note that support for position: sticky is spotty, however. It is not supported in some of the semi-recent versions of Edge, Firefox and Chrome, along with not being supported in Internet Explorer at all.

Also note that even in a valid browser, position: sticky will not work when the parent element has either overflow: hidden or overflow: auto.

Hope this helps :)

Upvotes: 0

Niels Vanhorenbeeck
Niels Vanhorenbeeck

Reputation: 164

You can indeed make use of event listeners to invoke css when your target hits the bottom of the page. You can find useful information on this guide:

https://developers.google.com/web/updates/2017/09/sticky-headers

Upvotes: 1

Related Questions