Css 如何阻止绝对定位图元的父级塌陷

Css 如何阻止绝对定位图元的父级塌陷,css,positioning,Css,Positioning,如何阻止绝对定位元素的父元素塌陷 在以下代码中,外部div的高度为0: <div id="outer" style="position: relative;"> <div id="inner" style="position: absolute; height: 100px;"> <p>This is the inner content.</p> </div> </div&g

如何阻止绝对定位元素的父元素塌陷

在以下代码中,外部div的高度为0:

<div id="outer" style="position: relative;">
    <div id="inner" style="position: absolute; height: 100px;">
        <p>This is the inner content.</p>
    </div>            
</div>

这是它的内在内容

这与这个问题非常相似,它涉及浮动元素,但是我尝试了一些解决方案(包括间隔符和clearfix类),但它们不起作用


谢谢

你不能:一旦孩子处于绝对位置,它实际上就在父母的“外面”(在外观上)

如果包含jquery,您可以做的是使用这种不合法的黑客攻击:

$(".absolutepos").each(function() {
    $(this).parent().css("height",$(this).height());
});
并在将div置于绝对位置时添加“absolutepos”类:

<div id="outer" style="position: relative;">
    <div id="inner absolutepos" style="position: absolute; height: 100px;">
        <p>This is the inner content.</p>
    </div>            
</div>

这是它的内在内容


你可以:我称之为“双亲制””:

在一个类似的挑战中,我最终定义了一个外部相对对象(作为浮动的子对象),以及一个绝对定义的与相对父对象具有相同维度的框,从共享(相对)父对象的0,0开始:一个相同的副本,其好处是允许将对象放置在其中,从而可以忽略浮动的外部限制(无论动态浮动的宽度如何,我都需要它将对象置于页面中心。)

“双亲制”解决了这两个问题:

  • 绝对父级无法获取浮动的高度(但能够适应浮动的共同父级的高度)
  • 相对父对象无法定位以页面为中心的对象(它只能找到浮动之间的中间位置,并防止居中的内容跨越浮动对象的边界)
  • 我做了一个演示,演示了这个设置如何在保持方框居中的同时挤压和挤压。下面的代码概述了基本思想:

    html (旁注:div的顺序(左-中-右,中-右-左,…)无关。)


    通过在内部DIV上使用绝对定位,您将其从页面流中移除。防止外部DIV折叠的唯一方法是设置其样式(可能使用
    min height
    padding top
    来匹配内部DIV的高度)。
    <header>
         <div class="header-left">left</div>
         <div class="header-center">
            <div class="centerinner">middle</div>
         </div>
         <div class="header-right">right</div>
    </header>
    
    header {
        position:relative; /* shrinkwrap to contained floats */
        /* display: block  /* no need to state this here */
        width: 100%;
        margin:0;
        padding:0;
        vertical-align: top;
        /* background-color: papayawhip; /* Debug */
    }
    .header-left { /* top left of header. header adapts to height */
        float:left;
        display:block;
        /* width and padding as desired */
    }
    .header-center { /* absolute reference for container box */
        position:absolute;
        left: 0;
        width: 100%;
        height:100%;
        /* background-color: gainsboro; /* Debug */
    }
    .centerinner { /* centered within absolute reference */
        margin-left:45%;
        margin-right:45%;
        padding-left: 1ex;
        padding-right: 1ex;
        background-color: #D6A9C9;
        width: -moz-fit-content;
        width: -webkit-fit-content;
        width: fit-content;
        height:100%;
    }
    .header-right {
        float:right;
        text-align: right;
        padding-left: 1ex;
        color: forestgreen;
     /* background-color: #D6F2C3; /* Debug */
    }