我的布局类似于:

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

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


当前回答

您可以使用内联块作为@user473598,但要注意较旧的浏览器。。

/* Your're working with */
display: inline-block;

/* For IE 7 */
zoom: 1;
*display: inline;

/* For Mozilla Firefox < 3.0 */
display:-moz-inline-stack;

Mozilla根本不支持内联块,但他们有-moz内联堆栈,这几乎是一样的

内联块显示属性周围的一些跨浏览器:https://css-tricks.com/snippets/css/cross-browser-inline-block/

您可以在以下位置看到一些具有此属性的测试:https://robertnyman.com/2010/02/24/css-display-inline-block-why-it-rocks-and-why-it-sucks/

其他回答

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

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

.div{
display:inline-block;
}

or

.div{
display:inline-flex;
}

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

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

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

div {
    display: inline-flex;
}

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

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

仅仅

<div style="display: inline;">
    <table>
    </table>
</div>