Html 使 div 宽度自动适应其中的内容
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7023654/
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
Make div width adapt automatically to contents within it
提问by Shades88
I have a div
within which a table
would lie. Now I want this div
to have its width set automatically to the width of table
within it.
我有一个div
在其中一个table
会撒谎。现在我希望div
它的宽度自动设置为其中的宽度table
。
For example:
例如:
<div>
<table>
<tr>
<td>Hello</td>
<td>World</td>
</tr>
<tr>
<td>Sample</td>
<td>Table</td>
</tr>
</table>
</div>
I tried giving float: left;
property to it. It works, but then it creates another problem. Whatever content is put after this div gets placed to the right of it in the empty space.
我试着给float: left;
它财产。它有效,但随后又产生了另一个问题。在这个 div 被放置在它右侧的空白空间之后,无论放置什么内容。
What needs to be done?
需要做什么?
采纳答案by Reto Aebersold
You have to clear the float after your div by adding style="clear: left;"on your consecutive element:
您必须通过添加style="clear: left;"来清除 div 后的浮动。在您的连续元素上:
<div style="float: left;">
<table>...</table>
</div>
<div style="clear: left;">
...
</div>
回答by Spycho
回答by Vandervals
This is quite new but...
这是很新的但是...
If you don't want the element to become inline-block, you can do this:
如果您不希望元素成为内联块,您可以这样做:
.parent{
width: min-content;
}
You have a lot of other options for configuring the width. Read more here: http://caniuse.com/#search=intrinsic
您还有很多其他选项可用于配置宽度。在此处阅读更多信息:http: //caniuse.com/#search=intrinsic
回答by emboss
回答by svanelten
If i understand correctly, you want the div to be as wide as the table but not any wider. Since the div-element is a block element, it will always be as wide as it can be unless you give it an explicit width.
Your choice is to either add the style display:inline
or use an inline-element like "span".
如果我理解正确,您希望 div 与表格一样宽,但不能更宽。由于 div 元素是一个块元素,它总是尽可能宽,除非你给它一个明确的宽度。您的选择是添加样式display:inline
或使用像“span”这样的内联元素。