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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 10:01:25  来源:igfitidea点击:

Make div width adapt automatically to contents within it

html

提问by Shades88

I have a divwithin which a tablewould lie. Now I want this divto have its width set automatically to the width of tablewithin 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

You are effectively attempting to change the display model of that div element, so you should change it's CSS 'display' property as follows:

您正在有效地尝试更改该 div 元素的显示模型,因此您应该按如下方式更改它的 CSS 'display' 属性:

div{
    display: inline-block;
}

Here's a jsFiddledemonstrating the solution.

这是一个jsFiddle演示解决方案。

回答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

You need to clear the float explicitly in order to not impair subsequent elements by the float. See this articlefor details.

您需要明确清除浮动,以免浮动影响后续元素。有关详细信息,请参阅此文章

回答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:inlineor use an inline-element like "span".

如果我理解正确,您希望 div 与表格一样宽,但不能更宽。由于 div 元素是一个块元素,它总是尽可能宽,除非你给它一个明确的宽度。您的选择是添加样式display:inline或使用像“span”这样的内联元素。