0

我需要一个绝对定位的 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/

4

2 回答 2

1

For the positioning problem, you'll have to rely on the magic of z-index ;) it is applicable to elements that have a non-static position (default is position: static). Therefore, have you considered absolutely positioning the .bg element, and relatively positioning the .caption element?

.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 */
}

In order to force the .bg element to be of the same dimension as .caption, you can use the dirty positioning trick - when an absolutely positioned element has the following properties declared:

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

It will fill to the size of the parent container - and in this case, the size of the parent container is determined by the content in .caption, since you have used a relative position for it (per my recommendation).

Here is a fiddle that shows how it works: http://jsfiddle.net/teddyrised/kbp6r/2/

于 2013-03-30T10:03:17.693 回答
1

Change your html as like below.

<div class="test1">
   <div class="bg">
      <div class="caption">Text that determines width of parent.</div>
   </div>
</div>
于 2013-03-30T10:12:50.620 回答