gpt4 book ai didi

html - 在没有高度属性的元素中使用 100% 高度

转载 作者:太空宇宙 更新时间:2023-11-04 14:57:36 24 4
gpt4 key购买 nike

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

Here is a fiddle .

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
}

正如您在 fiddle 和这段代码中看到的,如果父 divdiv 只会扩展以填充父 div > 具有固定的 height 属性。

但是,我不想使用固定高度。我希望父 div 的高度能够改变。如何让我的 child div 展开以填充父级而不在父级上使用固定高度?

最佳答案

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

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

此处演示:http://jsfiddle.net/9gePs/

关于html - 在没有高度属性的元素中使用 100% 高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16825558/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com