Advertisement
Advertisement


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


Question

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.

2019/11/19
1
2132
11/19/2019 12:51:17 PM


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.

2012/08/08

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):

HTML:

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

CSS:

.yourdiv
{
    display: inline;
}
2013/07/25

display: inline-block adds an extra margin to your element.

I would recommend this:

#element {
    display: table; /* IE8+ and all other modern browsers */
}

Bonus: You can also now easily center that fancy new #element just by adding margin: 0 auto.

2018/12/17

You can try fit-content (CSS3):

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

There are two better solutions

  1. display: inline-block;

    OR

  2. display: table;

Out of these two display:table; is better, because display: inline-block; adds an extra margin.

For display:inline-block; you can use the negative margin method to fix the extra space

2019/04/15

Source: https://stackoverflow.com/questions/450903
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]