How to place a sticky element above other elements without impacting their dimensions

68 Views Asked by At

I'm having a problem with positioning the floating sticky element on the right side with other elements not being impacted. As you can see in the image below, there are multiple "I'm full width I'm full width I'm full width..." elements. First few are shrunk in width due to a sticky element being positioned on the right side. However, the width of all the elements below are not impacted by the sticky element.

sticky element

I want ALL elements to have the full width, and have the sticky element on the right side.

Here's an example with the explained issue: https://codesandbox.io/s/late-night-d7f4jv?file=/index.html

1

There are 1 best solutions below

2
4D_Liam On

I have a solution for you but it is not the best...

<div style="
  width:100%;
  height:200vh;
  background-color:green;
  position:relative
 ">
  <div
    style="
      width:60%;
      height:50vh;
      margin-left:auto;
      background-color:pink;
      position:sticky;
      top:0;
      z-index:2"
  >
    <h1>I'm Sticky!</h1>
  </div>
  <div style="
    position:absolute;
    z-index:1;
    top:0
   ">
    <h2>I'm full width I'm full width I'm full width I'm full width I'm full width I'm full width</h2>
    <h2>I'm full width I'm full width I'm full width I'm full width I'm full width I'm full width</h2>
    <h2>I'm full width I'm full width I'm full width I'm full width I'm full width I'm full width</h2>
    <h2>I'm full width I'm full width I'm full width I'm full width I'm full width I'm full width</h2>
    <h2>I'm full width I'm full width I'm full width I'm full width I'm full width I'm full width</h2>
    <h2>I'm full width I'm full width I'm full width I'm full width I'm full width I'm full width</h2>
    <h2>I'm full width I'm full width I'm full width I'm full width I'm full width I'm full width</h2>
    <h2>I'm full width I'm full width I'm full width I'm full width I'm full width I'm full width</h2>
    <h2>I'm full width I'm full width I'm full width I'm full width I'm full width I'm full width</h2>
    <h2>I'm full width I'm full width I'm full width I'm full width I'm full width I'm full width</h2>
  </div>
</div>

I have moved your <h2> content into a separate <div> and changed the position to being absolute. This allows the content to spread without restrictions from the DOM. I used z-index to ensure the sticky element would stay at the front of the page and changed from using float values to just applying a margin-left: auto.

Not the most elegant solution...