Html 如何根据内容动态增加 <div /> 的高度?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3504246/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to dynamically increase the height of a <div /> based on the contents?
提问by DaveDev
I have a div on a page that I need to put content into. Sometimes the content is a few lines high, and sometimes the content is more than the screen height with varying sizes in between.
我在需要放入内容的页面上有一个 div。有时内容高几行,有时内容超过屏幕高度,两者之间的大小不一。
There is content below the div so I need that content to be pushed down appropriately, so the content below is always right below the div.
div 下方有内容,因此我需要将该内容适当向下推,因此下方的内容始终位于 div 的正下方。
Basically, it looks as follows:
基本上,它看起来如下:
<div id="MainContentArea"><!-- my content --></div>
<div id="BottomContentArea"><!-- pre-existing content --></div>
It's easy for me to specify a height for the #MainContentArea but I want the height to be adjusted dynamically. Can somebody please show me how to do this? Thanks.
我很容易为 #MainContentArea 指定高度,但我希望动态调整高度。有人可以告诉我如何做到这一点吗?谢谢。
回答by NibblyPig
Don't specify a height, and the div will automatically resize with the contents.
不要指定高度,div 会随着内容自动调整大小。
If you need a minimum size, there is a CSS property called min-height
that sets the minimum height of the div.
如果您需要最小尺寸,可以使用一个 CSS 属性min-height
来设置 div 的最小高度。
回答by Ethan Shepherd
Resizing vertically to fit the content is the expected behavior. If you have specified floats somewhere in your css you may need to clear them:
垂直调整大小以适应内容是预期的行为。如果您在 css 中的某处指定了浮点数,则可能需要清除它们:
<div style="clear:both;"></div>
回答by Cicil Thomas
#MainContentArea
will always expand dynamically since its height is assigned as auto.
#MainContentArea
将始终动态扩展,因为它的高度被指定为自动。
Since both have the same width, #BottomContentArea
will be pushed down.
由于两者具有相同的宽度,#BottomContentArea
将被推下。
Instead of percentage, use exact widths.
而不是百分比,使用精确的宽度。
<div id="MainContentArea" style="float:left;height:auto;width:100%;">
<!-- my content -->
</div>
<div id="BottomContentArea" style="float:left;height:auto;width:100%;s">
<!-- pre-existing content -->
</div>
回答by Liam Spencer
The height should resize automatically, and the bottom DIV should be pushed down in accordance with this height.
高度应自动调整大小,底部DIV应根据此高度向下推。