2013-03-30 278 views
0

我需要一个绝对定位的div,并包含两个子div:一个文本位于顶部,另一个底部为背景色。像这样:绝对div中100%div,没有宽度和固定高度

<div class="test1"> 
    <div class="caption">Text that determines width of parent.</div> 
    <div class="bg"></div> 
</div> 

我知道我可以只设置背景颜色上.test1,但我需要这样的背景下是一个单独的div来给我向后兼容(IE 7+)控制的位置,不透明度,宽度等使用jQuery。

使用以下CSS,除了文本位于.bg div之外,我可以使所有内容都可以工作。我需要顶部的文字。

<style type="text/css"> 
.test1 { 
    position: absolute; 
    left: 100px; 
    top: 100px; 
} 
.test1 .caption { 
    float: left; 
    white-space: nowrap; 
} 
.test1 .bg { 
    height: 50px; 
    background-color: #222; 
} 
</style> 

我怎么能有.test1的宽度是基于文本的宽度,并有.bg格是100%的宽度和.caption底下?我应该重申,这需要在IE 7及更高版本中运行。

这里有一个小提琴:http://jsfiddle.net/kbp6r/

回答

1

对于定位的问题,你必须依靠z-index魔术;)是适用于具有非静态的位置元素(默认为position: static)。因此,您是否考虑绝对定位.bg元素,并相对定位.caption元素?

.test1 .caption { 
    position: relative; 
    white-space: nowrap; 
    z-index: 2; /* More than .bg so it will be above */ 
} 
.test1 .bg { 
    position: absolute; 
    top: 0; 
    left: 0; 
    right: 0; 
    bottom: 0; 
    z-index: 1; /* Less than .caption so it will be stacked underneath */ 
} 

为了迫使.bg元素是相同尺寸为.caption,您可以用肮脏的定位绝招 - 当一个绝对定位的元素具有以下属性声明:

top: 0; 
left: 0; 
bottom: 0; 
right: 0; 

它将填充到父容器的大小 - 在这种情况下,父容器的大小由.caption中的内容决定,因为您已使用它的相对位置(根据我的建议)。

这里是一个小提琴,显示它是如何工作:http://jsfiddle.net/teddyrised/kbp6r/2/

+0

谢谢!很棒。 – Gavin

+0

@Gavin我很高兴它帮助:) – Terry

1

更改HTML像下面。

<div class="test1"> 
    <div class="bg"> 
     <div class="caption">Text that determines width of parent.</div> 
    </div> 
</div> 
+0

这解决了我问的问题,但是我需要独立的背景,因为我将添加效果,并且我不希望文字受到影响。 – Gavin

相关问题