问题设置父div宽度与子div宽度相同

时间:2011-09-15 16:22:56

标签: javascript jquery html css width

我有以下标记:

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

我希望img元素伸展到'head_title'div的整个宽度。当我尝试将'head_title'div设置为与'ent​​ryTitle'子h1标签一样宽时,麻烦就到了。这是我正在使用的CSS:

.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;
}

底层img元素包含父div的背景 - 我不想使用CSS background-image属性,因为父div的宽度将不断变化,我不希望它切断静态背景图像。

我尝试使用JavaScript的outerWidth和jQuery的.css("width").width()方法,但似乎没有任何效果。

2 个答案:

答案 0 :(得分:2)

这些元素的宽度为0px,因为您已将float:left属性分配给div.head_title。由于这个浮点定义,div不会拉伸到整个宽度。

图像的宽度为100%,零的100%仍为零。 h1元素绝对定位,因此元素也不会增加宽度。

要增加div.head_title的宽度,您必须指定宽度(例如width:!00%),或删除浮动属性。

答案 1 :(得分:1)

或者你也可以这样做....

<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

相关问题