Html 如何让一个div随着内容增长?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4657148/
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 make a div grow with content?
提问by funk-shun
Pertaining to html, how do I make a div container grow with the content instead of manually defining a width and height.
关于 html,如何让 div 容器随着内容增长,而不是手动定义宽度和高度。
<div id="container">
<div id="logo">
<img src="someimage.png"/>
</div>
</div>
No matter what the dimensions of logo are, container does not grow with it. :( How would I fix this, or can it be fixed?
无论标志的尺寸是多少,容器都不会随之增长。:( 我将如何解决这个问题,或者可以解决这个问题吗?
回答by stecb
If you don't define width and/or height, the div element grows along with its content. Unless his content is set to absolute! If the content is set to float, you have to set to the container
如果你没有定义宽度和/或高度,div 元素会随着它的内容增长。除非他的内容设置为绝对!如果内容设置为浮动,则必须设置为容器
overflow:hidden
in order to let it grow!
为了让它成长!
回答by tdammers
The default behaviour for divs is to fill the entire available width. A few ways to override this:
div 的默认行为是填充整个可用宽度。覆盖它的几种方法:
- set
display: inline-block
(not IE-friendly) - float it (with the side effect of, well, floating it)
- set
display: inline
(but that's almost never what you want) - set
position: absolute
- hard-code a width (no dynamic width though)
- 设置
display: inline-block
(对 IE 不友好) - 浮动它(有副作用,好吧,浮动它)
- 设置
display: inline
(但这几乎从来不是你想要的) - 放
position: absolute
- 硬编码宽度(虽然没有动态宽度)
As a last resort, consider javascript.
作为最后的手段,请考虑使用 javascript。
回答by molham556
Use the magical css property called "flex", it is really amazing
使用神奇的css属性叫做“flex”,真的很神奇
yourDiv{
display:flex;
}
Just make sure that the children are not position: absolute because this will not work with flex.
只要确保孩子不是 position: absolute ,因为这不适用于 flex。
回答by FrenkyB
You can specify min-width and min-height and DIV will adjust width / height as the content changes (of course, not below min width/height).
您可以指定 min-width 和 min-height,DIV 将随着内容的变化调整宽度/高度(当然,不会低于最小宽度/高度)。
Most important css properties from the code (DIV is editable, so just type in text and it will grow with it by width / height):
代码中最重要的 css 属性(DIV 是可编辑的,因此只需输入文本,它就会随宽度/高度一起增长):
min-height: 200px;
min-width: 100px;
回答by m.edmondson
Do you have sample code? A div will always be the full width of its container as its a block-levelelement.
你有示例代码吗?作为块级元素,div 将始终是其容器的整个宽度。