Skip to Main Content

Fixed Positioning within a Container

Today I've been working on a site where I have a list of icons that need to be fixed position on the right side of the container of the site. The issue with this is that fixed position items are removed from the document flow and thus are positiioned relative to the window. In a responsive site then it is not possible to place the element on the edge of the container since it's not possible to know where that edge is? Or is it?

Today I've been working on a site where I have a list of icons that need to be fixed position on the right side of the container of the site. The issue with this is that fixed position items are removed from the document flow and thus are positiioned relative to the window. In a responsive site then it is not possible to place the element on the edge of the container since it's not possible to know where that edge is? Or is it?

Some googling and I discovered that the solution to fixed positioning an element within a container is to not use top: or left: instead using margin-left and margin-top: to position. I tested by changing my css to the following and confirmed that it worked.:

    
      .iconMenu {
	position: fixed;
	margin-left: 1170px;
}
    
  

Unfortunatley as soon as you resize the browser the element is no longer positioned correctly. The solution was a little bit of jquery. I've wrapped everything in a media query because at mobile size this menu is positioned differently.

On line 6 get the width of the container and on line 7 set margin-left of the target element to that width minus a little bit to take into account the width of the iconMenu. Also have window.resize so that the element will remain positioned correctly even when the browser is resized.

    
      $(document).ready(function(){
 
if (window.matchMedia('(min-width: 768px)').matches)
{
  $(window).resize(function(){       
        var containerWidth = $('.container').width();
        $('.iconMenu').css('margin-left', containerWidth - 10);
        $('#home .iconMenu').css('margin-left', containerWidth - 25);
 
        // remove class so that menu is vertical
        $('.iconMenu').removeClass('list-inline');
    });       
    $(window).resize();
} else {
  // add class to make menu horizontal
  $('.iconMenu').addClass('list-inline');
}
 
 
});
    
  

Really not too difficult, hopefully this helps someone.