我的布局类似于:

<div>
    <table>
    </table>
</div>

我希望div只扩展到表的宽度。


当前回答

我尝试了div.classname{display:table cell;},结果成功了!

其他回答

<table cellpadding="0" cellspacing="0" border="0">
    <tr>
        <td>
            <div id="content_lalala">
                this content inside the div being inside a table, needs no inline properties and the table is the one expanding to the content of this div =)
            </div>
        </td>
    </tr>
</table>

我知道人们有时不喜欢表格,但我必须告诉你,我尝试了css内联技巧,它们在一些div中有点奏效,但在其他div中没有,所以,将扩展的div封装在表格中真的很容易。。。和它可以有内联属性,也可以没有内联属性,但表仍然是保持内容总宽度的表。=)

您可以尝试fit内容(CSS3):

div {
  width: fit-content; 
  /* To adjust the height as well */ 
  height: fit-content;
}

浏览器支持规格

如果我们定义一个全局变量并将其用于这两个变量会怎么样。

:根目录{--表格宽度:400px;}.容器{width:var(--表格宽度);边框:1px实心黑色;//易于可视化}.内表{width:var(--表格宽度);边框:1px纯红色;//易于可视化}<div class=“container”><table class=“inner table”><tr><td>美国广播公司</td></tr></table></div>

<div class="parentDiv" style="display:inline-block">
    // HTML elements
</div>

这将使父div宽度与最大元素宽度相同。

有两种更好的解决方案

显示:内联块;或显示:表格;

其中有两个显示:表;更好,因为显示:内联块;增加额外的边距。

用于显示:内联块;可以使用负边距方法来修复多余的空间