css html width

How can I make a div not larger than its contents?


I have a layout similar to:


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


  • 102

    the effect is called “shrinkwrapping”, and as answered there’s a couple of ways to do this (float, inline, min/max-width) all of which have side-effects to choose from

    – annakata

    Jan 16, 2009 at 16:32


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.


  • 39

    I would say inline-block is exactly intended for this and solves the problem perfectly.

    – miahelf

    Nov 17, 2011 at 8:24

  • @miahelf – Famous last words, at no point was inline-block the perfect way for this, and never will it be considered as such.

    – thephpdev

    Nov 30, 2021 at 9:57


I think using

display: inline-block;

would work, however I’m not sure about the browser compatibility.

Another solution would be to wrap your div in another div (if you want to maintain the block behavior):


    <div class="yourdiv">


    display: inline;


  • 23

    To answer the browser compatibility question: this won’t work with IE7/8 on DIV elements. You have to use SPAN elements.

    Feb 18, 2011 at 14:26