0
votes

I have the following code:

<div class="main">
   <!-- CONTENT --> 
 <div class="tabs">
   <!-- CONTENT --> 
 </div>  <!-- Closing div for .tabs -->
 </div>  <!-- Closing div for .main -->

.tabs{
  position: fixed;
  top:110px;
  left:0px;
  width:40px;
  z-index:999
}
.main{
  overflow: hidden;
  margin: 0 0 100px;
  box-shadow: 0 10px 16px rgba(0,0,0,0.33);
  border-radius: 0px 0px 25px 25px;
  position:relative;
}

From my understanding position:fixed is always relative to the browser window not the containing element. However I would prefer the .tabs div to be fixed but relative to the containing div. Is there anyway to have position fixed and have it relative to the containing element?

1
Use position: absolute. - reinder
@reinder - I could but I want the div to stay fixed on the page and not scroll off. - L84
In that case you will need some javascript to calculate the position of the containing div. Fixed is always relative to the browser window (viewport) no matter what. - reinder
@reinder - Feel free to write that into an answer. JS is not always my strong suit => - L84

1 Answers

1
votes

As pointed out this is a duplicate. The question referred to however assumes that the width of the containing element is known. If that's not the case you will need some javascript. I made an example here: http://jsfiddle.net/6TyL4/

Please note that since fixed basically takes the element out of the container, the container element will not adjust in height width etc. and therefore doesn't actually "contain" the element.

$(function(){
    var t = $('.main').position().top;
    var l = $('.main').position().left;
    $('.tabs').css('top', t + 100).css('left', l + 100);
});

This will offset the .tabs 100px from the top and from the left relative to '.main'.