hohner
hohner

Reputation: 11588

Problem setting parent div width the same as child div width

I have the following markup:

<div class="head_title">
  <img src="/path/to/image.png">
  <h1 id="entryTitle">
    <!--Cufon Font-->
  </h1>
</div>

I want the img element to stretch to the full width of the 'head_title' div. The trouble arrives when I try and set the 'head_title' div to be as wide as the 'entryTitle' child h1 tag. Here's the CSS I'm using:

.head_title {
    display:block;
    float:left;
    position:relative;
    height:40px;
}
.head_title img {
        height:100%;
        width:100%;
        display:block;
}
.head_title h1 {
        color:#fff;
        position:absolute;
        top:0;left:0;
        z-index:1;
        padding:0 0 0 5px;
}

The underlying img element contains the background for the parent div - I don't want to use the CSS background-image attribute because the parent div's width will constantly be changing and I don't want it to cut off a static background image.

I tried using JavaScript's outerWidth and jQuery's .css("width") and .width() methods but nothing seems to work.

Upvotes: 2

Views: 2640

Answers (2)

rlemon
rlemon

Reputation: 17666

or you could also do this....

<div class="head_title">
  <img src="/path/to/image.png">
  <h1 id="entryTitle">
    <!--Cufon Font-->
  </h1>
</div>

.head_title{
    float: left;
    position:relative;height:40px;
}
.head_title img {
    position:absolute;top:0;left:0;z-index:-1; width: 100%; height: 100%;
}
.head_title h1{color:#999;padding:0 0 0 5px;}

sample here

Upvotes: 1

Rob W
Rob W

Reputation: 348972

These elements have a width of 0px, because you assigned the float:left property to div.head_title. Because of this float definition, the div doesn't stretch to the full width.

The image has a width of 100%, 100% of zero is still zero. The h1 element is positioned absolutely, so that element doesn't increase the width either.

To increase the width of div.head_title, you have to specify a width (width:!00%, for example), or remove the float property.

Upvotes: 2

Related Questions