Why Doesn't CSS Fixed Positioning Consider the

2019-08-13 08:30发布

问题:

It's my understanding that a CSS fixed position element is relative to the viewport only. However, from what I can tell, this is true except that if "left" is unspecified, it doesn't default to 0 but rather to the left edge of what would have otherwise been its container - in this case, the main div. The HTML:

<div id="main">
    <div id="fixed"></div>
    <div id="content"></div>
</div >

The CSS:

#main{
    width:80%;
    margin-left:auto;
    margin-right:auto;
}
#fixed{
    position:fixed;
    width:100%;
    height:25px;
    background:yellow;
}
#content{
    width 100%;
    height:300px;
    background:red
}

demonstrated at http://jsfiddle.net/2dudX/99/ . If I specify left:0 the fixed element will run the width of the screen. What causes this behavior? What are the defaults if I don't specify a left, right, top or bottom?

回答1:

The behavior that you are seeing is correct.

If you set position property to a value of absolute or fixed, and the offsets are not specified, then the element is positioned to the static position, that is, the position it would take with position: static.

However, the difference is that the element with position absolute/fixed is taken out of normal document flow regardless of the offset values (auto or explicitly specified).

Reference: http://www.w3.org/TR/CSS2/visudet.html#abs-non-replaced-width

Specifically, the section around (my paraphrase):

if 'left' and 'right' are 'auto' and 'width' is not 'auto', then set 'left' to the static position and then solve for 'right'

If you want to understand how height is affected by the offsets, see the following:
http://www.w3.org/TR/CSS2/visudet.html#abs-non-replaced-height