我的布局类似于:

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

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


当前回答

我认为使用

display: inline-block;

但我不确定浏览器的兼容性。


另一种解决方案是将您的div包装在另一个div中(如果您想保持块行为):

HTML格式:

<div>
    <div class="yourdiv">
        content
    </div>
</div>

CSS:

.yourdiv
{
    display: inline;
}

其他回答

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

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

浏览器支持规格

在Firebug中我发现了属性值-moz fit content,它完全符合OP的要求,可以如下使用:

width: -moz-fit-content;

虽然它只在Firefox上运行,但我找不到其他浏览器(如Chrome)的等效版本。

这似乎是一个13年前的问题。

.div{
display:inline-block;
}

or

.div{
display:inline-flex;
}

现在可以工作几天,没有任何兼容性问题。

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

尝试使用width:max-content属性根据div的内容大小调整其宽度。

试试这个例子,

<!DOCTYPE html>
<html>
<head>
<style>
div.ex1 {
  width:500px;
  margin: auto;
  border: 3px solid #73AD21;
}

div.ex2 {
  width: max-content;
  margin: auto;
  border: 3px solid #73AD21;
}
</style>
</head>
<body>

<div class="ex1">This div element has width 500px;</div>
<br>
<div class="ex2">Width by content size</div>

</body>
</html>