Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fixed position div not staying contained in wrapping div, overlays entire screen?

Tags:

html

css

I'm trying to make a fixed position div stay within an outer div. I want the fixed position div's width to be 100%. However, when I set the width to 100%, the fixed position div covers the entire screen and overlays the scrollbar in Firefox/IE8 etc. Here is a sample of what I'm talking about:

<div style="width: 380px; height: 125px;overflow-y: scroll;overflow-x: hidden;">
    <div style="position:fixed;width:100%;">
        <div style="width: 100%;background: red; text-align: center; height:50px;">header</div>
    </div>

    <div style="margin-top: 50px; height:250px;">
        Contents here<br />
        Contents here<br />
        Contents here<br />
        Contents here<br />
        Contents here<br />
    </div>
</div>

As you can see, the outer div has a width of 380 pixels... so, I would not think it possible for the fixed position div to extend outside of this boundary, yet it does.

What am I doing wrong?

Thanks!

like image 974
Polaris878 Avatar asked Feb 28 '11 20:02

Polaris878


2 Answers

An element with fixed position is positioned relative to the viewport. Fixed positioned elements are removed from the normal flow. The document and other elements behave like the fixed positioned element does not exist.

Although you declare position:fixed;, you don't specify a value for the top and left properties. The default value for both properties is auto, which lets the browser calculate the top edge and left edge positions. The calculated edge positions turn out to be the element's top and left edge positions in the normal flow, which is why it moves when you set a margin.

like image 64
melhosseiny Avatar answered Oct 24 '22 10:10

melhosseiny


Fixed is always relative to the parent window, never an element. Once the position is set to fixed its taken out of the document flow.

http://www.w3.org/TR/CSS2/visuren.html#fixed-positioning

Fixed positioning is a subcategory of absolute positioning. The only difference is that for a fixed positioned box, the containing block is established by the viewport.

like image 4
Loktar Avatar answered Oct 24 '22 08:10

Loktar