我的布局类似于:

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

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


当前回答

<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封装在表格中真的很容易。。。和它可以有内联属性,也可以没有内联属性,但表仍然是保持内容总宽度的表。=)

其他回答

评论中提到了这一点,在其中一个答案中很难找到:

如果出于任何原因使用display:flex,则可以改用:

div {
    display: inline-flex;
}

这在浏览器中也得到广泛支持。

只需设置宽度和高度以适合内容。这很简单。

div {

    width: fit-content;
    height: fit-content;
    padding: 10px;

}

我正在添加填充:10px;。如果省略了它,div元素将完全与表保持一致,看起来有点笨拙。填充将在元素的边界与其内容之间创建给定的空间。但这是你的愿望,不是强制性的。

不知道这将出现在什么上下文中,但我相信CSS样式的属性float(向左或向右)将产生这种效果。另一方面,它也会有其他副作用,例如允许文本在其周围浮动。

如果我错了,请纠正我,我不是100%确定,目前无法自己测试。

    .outer{
          width:fit-content;   
          display: flex;
          align-items: center;
    }
    .outer .content{
         width: 100%;
    }
        
        
        
        
<div class=outer>
    <div class=content>
       Add your content here


    </div>
        
</div>

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

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