How to make div not larger than its contents?

2018-12-31 03:29发布

I have a layout similar to:

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

I would like for the div to only expand to as wide as my table becomes.

标签: html css width
30条回答
其实,你不懂
2楼-- · 2018-12-31 04:18

The solution is to set your div to display: inline-block.

查看更多
临风纵饮
3楼-- · 2018-12-31 04:18

You can use inline-block as @user473598, but beware of older browsers..

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

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

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

Mozilla doesn’t support inline-block at all, but they have -moz-inline-stack which is about the same

Some cross-browser around inline-block display attribute: https://css-tricks.com/snippets/css/cross-browser-inline-block/

You can see some tests with this attribute in: https://robertnyman.com/2010/02/24/css-display-inline-block-why-it-rocks-and-why-it-sucks/

查看更多
姐姐魅力值爆表
4楼-- · 2018-12-31 04:18

I would just set padding: -whateverYouWantpx;

查看更多
不流泪的眼
5楼-- · 2018-12-31 04:19
width:1px;
white-space: nowrap;

works fine for me :)

查看更多
墨雨无痕
6楼-- · 2018-12-31 04:20

I have solved a similar problem (where I didn't want to use display: inline-block because the item was centered) by adding a span tag inside the div tag, and moving the CSS formatting from the outer div tag to the new inner span tag. Just throwing this out there as another alternative idea if display: inline block isn't a suitable answer for you.

查看更多
琉璃瓶的回忆
7楼-- · 2018-12-31 04:21

You want a block element that has what CSS calls shrink-to-fit width and the spec does not provide a blessed way to get such a thing. In CSS2, shrink-to-fit is not a goal, but means to deal with a situation where browser "has to" get a width out of thin air. Those situations are:

  • float
  • absolutely positioned element
  • inline-block element
  • table element

when there are no width specified. I heard they think of adding what you want in CSS3. For now, make do with one of the above.

The decision not to expose the feature directly may seem strange, but there is a good reason. It is expensive. Shrink-to-fit means formatting at least twice: you cannot start formatting an element until you know its width, and you cannot calculate the width w/o going through entire content. Plus, one does not need shrink-to-fit element as often as one may think. Why do you need extra div around your table? Maybe table caption is all you need.

查看更多
登录 后发表回答