Absolute and fixed positioning together

Create a fixed scrolling sidebar with no JavaScript and a few lines of CSS.

The fixed div in the fiddle below appears to be positioned relative to the container but this is just an illusion.

It can be achieved using percentage widths or by using fixed widths and the setting a negative margin relative to the container width.

FLUID WIDTH

.wrap {
  background: #ccc;
  width: 90%;
  height: 1000px;
}

.fixed {
  position: fixed;
  top: 10px;
  right: 0;
  background: #333;
  height: 100px;
  width: 10%;
}
<div class="wrap">WRAP</div>
<div class="fixed">FIXED</div>

FIXED WIDTH

.wrap {
  background: #ccc;
  width: 200px;
  height: 1000px;
  margin: 0 auto;
}

.fixed {
  position: fixed;
  top: 20px;
  right: 50%;
  background: #333;
  height: 100px;
  width: 50px;
  margin-right: -160px;
}
<div class="wrap">WRAP</div>
<div class="fixed">FIXED</div>

A note about CSS positioning.

FIXED

Element is always positioned relative to the screen.

ABSOLUTE

Element is positioned relative to the nearest parent container with a position attribute.


You can also use calc() to achieve this. (supported in IE9+):

.fixed {
    position: fixed;
    right: calc(50% - 360px); 
    /* Replace 360px with half of container width plus desired positioning */
}

or if you want your fixed div on the left, for instance:

.fixed {
    position: fixed;
    left: calc(50% - 360px); 
    /* Replace 360px with half of container width plus desired positioning */
}

Well, the inspected element IS absolute positioned, but is placed inside a wrapper (in another parent element) - #player-modal, which is fixed positioned!

The absolute position is used inside the fixed positioned parent, so the .hud element to be just a few pixels outside the content area (same spacing in every resolution!). This way the floating is fixed to the content area, instead of depending on the resolution (using fixed positioning + using the "right: 20px;" setting).

I just forgot to mention that it's possible, because the site has fixed width and not responsive layout, adjusting to every resolution. If you plan to use this efect on site with fixed width - it will work, otherwise you could need another solution.

I hope I've explained it well! :-)


This is the only way I've found: like @DreamTek said:

<div id="relative-layer">
    <div id="fixed-layer">
    </div>
</div>

and in the styles file:

#relative-layer {
    position:relative;
}

#fixed-layer {
    position: fixed;
    margin-top: 10px;
    margin-left: 10px;
}

because using top and right rules positions the layer relative to the window, but if using margin-top and margin-left it is positioned relative to the parent layer.

JSFIDDLE: http://jsfiddle.net/9HQ4b/1/