How can I fix an element to the page that is of a variable distance from the edge of the screen?

62 views Asked by At

I have a graphic that I need to appear as a sticky element 66% of the way across the container div of my webpage. 'position:fixed' would normally be exactly what I want, however, since this fixes to the viewport and the container div is sometimes an unknown distance from the edge of the viewport, I can't use it to determine the precise horizontal point at which it should display.

Some more info: The container div is responsive and a maximum of 1080px, centered in the viewport when the viewport is wider than 1080px. So the position of this graphic can be determined with reference to the viewport only up to 1080px wide. Beyond that point, the graphic needs to appear at [(total-width-of-viewport-1080px)/2 + 66% of 1080px]. No idea how to render that with CSS!

Another approach that occurred to me is to use absolute positioning to fix the element precisely to the container div and use some jquery magic to update the vertical position with regards to the viewport top as the user scrolls to give it a 'sticky' quality. However, all solutions I've found for this approach seem like massive overkill for what I want to achieve.

I'd be really grateful for any solutions or advice.

Edit: I've attached an image to illustrate the problem: https://i.stack.imgur.com/KX9xw.png

2

There are 2 answers

0
Andrew On BEST ANSWER

Thanks to DSMann8 alerting me to the existence of both calc() and VW and a little bit of googling, I've solved the problem. Here is the full CSS for the element I was trying to position, for anyone interested:

span#scissors {
  background: transparent url(../imgs/new/scissors.png) no-repeat left top;
  display: block;       
  width: 16px;
  height: 34px;
  position: fixed;  
  top: 400px;
}

@media (max-width: 1080px) {
  span#scissors {
    left: calc(66VW - 8px);
  }
}
@media (min-width: 1079px) {
  span#scissors {
    left: calc(((100VW - 1080px) / 2) + (1080px * 2/3));
    margin-left: -8px;
  }
}

Thank you all who helped!

1
JNF On

Give the outer div a position:relative and the inner one a position:absolute.

Run the snippet in full screen and play with window size. you can also change window size in this fiddle

#wrapper{
    max-width: 600px;
    width: 100%;
    position: relative;
    top: 0px;
    right: 0px;
    background: goldenrod;
    height: 300px;
}

#elem {
    width: 66%;
    position: absolute;
    top: 0px;
    right: 0px;
    background: royalblue;
    height: 300px;
}
<div id="wrapper">
    <div id="elem">
    </div>
</div>