0

height: 100%内の要素で使用すると、高さが固定され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 に答える