Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fixed positioned div within a relative parent div

Tags:

css

fixed

I am currently building a responsive website and need a menu to be fixed, thus not scrolling when the rest of the site scrolls. the issue is that it is a fluid layout and i want the "fixed positioned" menu item to be fixed relative to the containing parent element and not to browser window. is there anyway this can be done?

like image 953
Gavin Wood Avatar asked Oct 21 '11 07:10

Gavin Wood


People also ask

Can position fixed be relative to parent?

fixed : the element is removed from the flow of the document like absolutely positioned elements. In fact they behave almost the same, only fixed positioned elements are always relative to the document, not any particular parent, and are unaffected by scrolling.

How can I make a div fixed inside another div?

Set position: absolute; on the element that you want to position. Set position: relative; on the centered div so that it becomes a layer that you can position elements inside.

When using position fixed What will the element always be positioned relative to?

An element with position: fixed; is positioned relative to the viewport, which means it always stays in the same place even if the page is scrolled. The top, right, bottom, and left properties are used to position the element.

Can a div be position absolute and relative?

If you position it as absolute , then you're positioning it relative to its closest ancestor which is fixed or relative ... Clearly, nothing can be absolute and relative at the same time. Either you want the element to position itself based on another ancestor's position or based on the page flow.


2 Answers

This question came first on Google although an old one so I'm posting the working answer I found, which can be of use to someone else.

This requires 3 divs including the fixed div.

HTML

<div class="wrapper">     <div class="parent">         <div class="child"></div>     </div> </div> 

CSS

.wrapper { position:relative; width:1280px; }     .parent { position:absolute; }         .child { position:fixed; width:960px; } 
like image 191
Leo Avatar answered Oct 04 '22 08:10

Leo


Gavin,

The issue you are having is a misunderstanding of positioning. If you want it to be "fixed" relative to the parent, then you really want your #fixed to be position:absolute which will update its position relative to the parent.

This question fully describes positioning types and how to use them effectively.

In summary, your CSS should be

#wrap{      position:relative; } #fixed{      position:absolute;     top:30px;     left:40px; } 
like image 26
Fuzzical Logic Avatar answered Oct 04 '22 09:10

Fuzzical Logic