我的布局类似于:
<div>
<table>
</table>
</div>
我希望div只扩展到表的宽度。
我的布局类似于:
<div>
<table>
</table>
</div>
我希望div只扩展到表的宽度。
当前回答
这似乎是一个13年前的问题。
.div{
display:inline-block;
}
or
.div{
display:inline-flex;
}
现在可以工作几天,没有任何兼容性问题。
其他回答
您可以尝试fit内容(CSS3):
div {
width: fit-content;
/* To adjust the height as well */
height: fit-content;
}
浏览器支持规格
尝试使用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>
您可以使用内联块作为@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/
我只需要设置填充:-whateverYouWantpx;
display: -moz-inline-stack;
display: inline-block;
zoom: 1;
*display: inline;
Foo Hack–对内联块样式的跨浏览器支持(2007-11-19)。