0

我发现height: 100%在 a 内的元素上使用时,除非包含它是固定高度,div否则它不起作用。div

这是一个小提琴

HTML

<div id='header' class='bodyRect'>
    <div id='welcome'>
        <h1>This is a welcome message</h1>
        <p>Welcome to this website.</p>
        <p>It is websitey.</p>
        <p>Click <a id='toggle' href='#'>here</a> to toggle fixed vs 100% height to see the problem.</p>
    </div>
    <div id='logo'></div>
    <span class='clearfix'></span>
</div>

CSS

body {
    text-align: center;
}
.bodyRect {
    border: 1px solid black;
    padding: 10px;
    margin: 10px;
}
#welcome {
    width: 70%; float: left
}
#logo {
    width: 30%; float: right;
    background-color: red;
    height: 100%;
}
.clearfix {
    display: block;
    clear: both;
    visibility: hidden;
    line-height: 0;
    height: 0;
}

JS(用于测试;它在固定高度和非固定高度之间切换,因此您可以看到问题)

var fixedHeight = false
document.getElementById('toggle').onclick = function(e) {
    e.preventDefault()
    fixedHeight = !fixedHeight
    var newHeight = fixedHeight ? '500px' : '100%'
    alert('height is now ' + newHeight)
    document.getElementById('logo').style.height = newHeight
}

正如您在小提琴和这段代码中看到的那样,如果父级具有固定属性,则子div级只会扩展以填充父级。divdivheight

但是,我不想使用固定高度。我希望父母的高度div能够改变。如何让我的孩子div在不使用父级的固定高度的情况下扩展以填充父级?

4

3 回答 3

1

实现这一点的唯一方法是将子 div 从文档流中取出。

将父级设置为position:relative;,将子级设置为position:absolute;

在这里演示:http: //jsfiddle.net/9gePs/

于 2013-05-29T23:35:32.970 回答
0
.childDiv{
 position: absolute;
 top: 0;
 left: 0;
 right: 0;
 bottom: 0;
}

如果父级具有相对位置,这将在所有方向上将其扩展为 100%。

于 2013-05-29T23:37:05.443 回答
0

可能不是您正在寻找的理想答案,但使用一些jQuery

$(function(){
      var logo_height_percent = 100;  //<-- set the percent here
      $('#logo').height($('#header').height() * logo_height_percent/100);
});

jsFiddle在这里

于 2013-05-29T23:50:33.317 回答