简体   繁体   中英

Relatively-positioned parent with absolutely-positioned children collapses the later elements

I have the following HTML:

<div id="contents">
    <div id="inner">Inner Div</div>
</div> 

<div id="footer">Footer</div>​

Applying the following CSS:

#contents {
    position: relative;
}

#inner {
    position: absolute;
    background-color: green;
    width: 100%;
}

#footer {
    background-color: red;
}​

Problem is that the #footer gets collapsed and under the #contents . You can check here on jsfiddle also http://jsfiddle.net/MAhmadZ/YkJMH/1/

Note: This is just an abstract from a larger page. I have no option but to use position properties. I have multiple div inside #contents all absolutely positions and only 1 will be showed at a time. I can't be sure of the height

Your #contents element is empty after #inner is taken out of the flow by absolute positioning, so it has zero height and as a result #footer collapses under it.

If you give #contents a height or some vertical padding, it should prevent #footer from sliding underneath your absolutely-positioned element.

This should fix it:

#contents {
    position: relative;
}

#inner {
    position: absolute;
    background-color: green;
    width: 100%;
}

#footer {
    background-color: red;
    position: absolute;
    width: 100%;
    bottom: 0;
}​

Your problem is #inner is positioned absolutely. This makes it invisible to the STATIC formatting of HTML layout.

不太确定要实现的目标,但可以将页脚设置为使用position:fixed和bottom:0px来将其保持在页面底部。

I have myself come up with the following solution:

#footer:before {
    content: '.';
    display: block;
    width: 100%;
}

Check it live: http://jsfiddle.net/MAhmadZ/YkJMH/5/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM