viery365 viery365 - 5 months ago 10x
CSS Question

Fixed element positioned relative to the viewport(left) and static element (right)

Probably this is impossible but I had to try:
Let's imagine an element fixed to the viewport.

Position: fixed;
Top: 30px;
Left: 0px;

But the right side relative to a certain element on the page (container) with
position: static
:enter image description here

I am aware that if I set the right position of the fixed element normally will be set relative to the right side of the viewport.

So, in this case, when resizing the browser the right side of the fixed element would not be relative to right side of the viewport but to the right side of the container.

Maybe some javaScript? jQuery?


Provided you know beforehand where the right edge of the "container" will lie (based on its width/left offset), you can achieve the desired layout in most modern browsers using the CSS3 calc() function. In pseudocode, your formula for right would look something like:

right: calc(100% - container_left_offset - container_width);

Here's a working demo of the code:

html {
  margin: 0;
#fixed {
  background: #CCC;
  height: 30px;
  left: 0;
  position: fixed;
  right: calc(100% - 100px - 300px);
  top: 30px;
#static {
  background: #999;
  height: 800px;
  margin-left: 300px;
  width: 100px;
<div id="fixed">
<div id="static">

However, if the right edge position of the container cannot be known beforehand (eg. Dynamic width/variable content), you'll probably have to take a JavaScript route. Hope this helps! Let me know if you have any questions.