簡體   English   中英

絕對div內的100%div,沒有寬度和固定高度

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM