【问题标题】:Absolute Positioning Relative to the Parent相对于父级的绝对定位
【发布时间】:2013-09-21 01:25:48
【问题描述】:

我的假设是在使用绝对定位时,它是相对于父 div 的。但是,这个 jsfiddle 似乎与此不符。我正在尝试做的是在中间行设置最小高度的三行液体布局。顶部和底部具有固定的高度。不幸的是,我只为 IE7 编写代码,并且没有在我的 CSS 中使用 min-height 的奢侈。使用 JQuery 时,中心会调整大小,但是,页脚不会相对于父级重新定位。下面的信息和jsfiddle。

浏览器:IE7

样式:CSS

HTML:4.0 严格

jQuery:1.10.1

jsfiddle

将 position:relative 和 height 100% 添加到 wrapper jsfiddle 后的小提琴

HTML

<div id="wrapper">
    <div id="top"></div>
    <div id="center"></div>
    <div id="bottom"></div>
</div>

CSS

html, body{
    width:100%;
    height:100%;
}
#wrapper{
    background-color:blue;
    height:100%;
    width:100%;
    margin:0px;
    padding:0px;
    min-width:700px;
}
#top{
    position:absolute;
    top:0px;
    width:100%;
    height:100px;
    min-width:700px;
    background-color:green;
}
#center{
    position:absolute;
    top:100px;
    bottom:20px;
    min-width:700px;
    width:100%;
    background-color:yellow;
}
#bottom{
    position:absolute;
    bottom:0px;
    min-width:700px;
    width:100%;
    height:20px;
    background-color:purple;
}

jQuery

var resizeTimer = false;
        function doResize() {
            if ($("body").height() == 500) {
                //do nothing
            }
            else if ($("body").height() < 500) {
                $("#wrapper").height(500);
                $("#center").height(380);

            }
            else {
                $("#wrapper").height("auto");
                $("#center").height("auto");
            }
            resizeTimer = false;
        }

        $(window).on("resize", function () {
            if (resizeTimer) {
                clearTimeout(resizeTimer);
            }
            resizeTimer = setTimeout(doResize, 300);
        });

【问题讨论】:

    标签: jquery height absolute css


    【解决方案1】:

    绝对定位是相对最近的父级(沿着父级链向上)设置了位置(如position: relativeposition: absolute)。如果父链中没有父链有定位设置,那么绝对定位是相对于文档边界的。

    如果您希望position: absolute 相对于父级,则在父级上设置position: relative。这不会改变父级的位置,但会将子级的定位范围限定为相对于父级而不是相对于某个更高级别的父级或文档。

    【讨论】:

    • 这会导致我的 div 在调整大小时出现奇怪的消失行为。请参阅新的 jsfiddle。
    • 从头开始。在 jquery 中需要 100% 而不是 auto。请参阅jsfiddle.net/wQAmA/1 的 js fiddle。从你是第一个开始,你就得到了接受。谢谢!
    • 我还注意到,如果父级有display: inline,定位会中断。使用display: block 作为父母来解决这个问题。
    【解决方案2】:

    位置不是相对于父级,而是相对于最近的具有定位的父级(或文档,如果没有父级具有定位)。

    position:relative 添加到父元素的CSS 中,使其具有定位,而无需实际将其移动到任何地方。

    【讨论】:

    • 这会导致我的 div 在调整大小时出现奇怪的消失行为。查看新的 jsfiddle
    • 从头开始。在 jquery 中需要 100% 而不是 auto。请参阅jsfiddle.net/wQAmA/1 的 js fiddle。
    猜你喜欢
    • 2021-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-19
    相关资源
    最近更新 更多