[英]100% div inside absolute div with no width and fixed height
我需要一个绝对定位的div,它包含两个子div:一个文本位于顶部,另一个背景颜色位于底部。 像这样:
<div class="test1">
<div class="caption">Text that determines width of parent.</div>
<div class="bg"></div>
</div>
我知道我可以在.test1上设置背景颜色,但我需要这个背景是一个单独的div,以便使用jQuery对位置,不透明度,宽度等进行向后兼容(IE 7+)控制。
使用以下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 div为100%宽度并位于.caption下面? 我应该重申,这需要在IE 7及更高版本中运行。
这是一个小提琴: http : //jsfiddle.net/kbp6r/
对于定位问题,您将不得不依赖于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/
如下所示更改您的HTML。
<div class="test1">
<div class="bg">
<div class="caption">Text that determines width of parent.</div>
</div>
</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.