【问题标题】:100% div inside absolute div with no width and fixed height绝对 div 内的 100% div,没有宽度和固定高度
【发布时间】:2013-03-30 09:53:55
【问题描述】:

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

【问题讨论】:

    标签: css html absolute


    【解决方案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/

    【讨论】:

    • @Gavin 我很高兴它有帮助:)
    【解决方案2】:

    如下更改您的 html。

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

    【讨论】:

    • 这解决了我的问题,但是我需要背景是独立的,因为我将为其添加效果并且我不希望文本受到影响。
    猜你喜欢
    • 2011-01-21
    • 1970-01-01
    • 1970-01-01
    • 2011-01-11
    • 2011-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多