简体   繁体   中英

100% div inside absolute div with no width and fixed height

I need to have a div that's absolutely positioned and contains two child divs: one with text that goes on top, and one with a background-color that's on the bottom. Like so:

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

I know I can just set a background color on .test1, but I need this background to be a separate div to give me backwards-compatible (IE 7+) control over the position, opacity, width, etc. using jQuery.

With the following CSS, I can get everything to work, except that the text is behind the .bg div. I need the text on top.

<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>

How can I have the width of .test1 be based on the width of the text and have the .bg div be 100% width and underneath .caption? I should repeat that this needs to work in IE 7 and above.

Here's a fiddle: http://jsfiddle.net/kbp6r/

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/

Change your html as like below.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM