2012-11-26 52 views
8

如何从折叠中阻止绝对定位元素的父母?如何阻止折叠的绝对定位元素的父母

在以下代码中,外部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> 

这是非常相似的这个问题,How do you keep parents of floated elements from collapsing?,其与浮动元素的交易,但是我尝试了一些解决方案的(包括分隔符和clearfix类),并且它们不起作用。

谢谢!

+3

通过使用在内部DIV绝对定位,你从页面的流量中删除。防止外部DIV崩溃的唯一方法是对其进行设计(可能使用“min-height”或“padding-top”来匹配内部DIV的高度)。 – joequincy

回答

3

你不能:一旦孩子处于绝对位置,它几乎是父母的“外部”(外表)。

你可以做什么,如果你已经包括jQuery的,就是用这个unelegant黑客:

$(".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> 
2

你可以:由我称为“双父母”:

在一个类似的挑战中,我最终定义了一个外部相对对象(父类化浮点数)和一个绝对定义的与相对父对象相同尺寸的框,从共享(相对)父对象的0,0开始:复制的好处是允许放置内容的对象能够忽略浮动的外部限制(我需要它将页面中心对象,无论动态浮动的宽度如何)。

“dual育儿“压扁了两个问题:

  1. 绝对父母无法获得浮动的高度(但能够适应浮动的双亲的高度)。
  2. 相对父代无法定位以页面为中心的对象(它只能找到浮动间的中间,并保持居中内容不能跨过浮动对象的边界)。

我做了一个fiddle (contains documentation),演示了如何在保持居中盒子的同时压扁和挤压。其基本思想是在下面的代码所示:

HTML (在一个侧面说明: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> 

CSS

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 */ 
} 
相关问题