By George Snider


2009-01-16 16:03:07 8 Comments

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.

30 comments

@Showrin Barua 2019-07-11 03:19:05

You can try this code. Follow the code in the CSS section.

div {
  display: inline-block;
  padding: 2vw;
  background-color: green;
}

table {
  width: 70vw;
  background-color: white;
}
<div>
    <table border="colapsed">
      <tr>
        <td>Apple</td>
        <td>Banana</td>
        <td>Strawberry</td>
      </tr>
      <tr>
        <td>Apple</td>
        <td>Banana</td>
        <td>Strawberry</td>
      </tr>
      <tr>
        <td>Apple</td>
        <td>Banana</td>
        <td>Strawberry</td>
      </tr>

    </table>
</div>

@Rehan Rabbani 2019-09-14 16:02:34

You can use height: 100% and width for your choice. This makes the div not larger than its content.

@nalm 2019-11-05 12:52:04

if u set height 100% it will be 100% of the window total size

@Edward 2011-08-03 16:59:09

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

I know people don't like tables sometimes, but I gotta tell you, I tried the css inline hacks, and they kinda worked in some divs but in others didn't, so, it was really just easier to enclose the expanding div in a table...and...it can have or not the inline property and still the table is the one that's gonna hold the total width of the content. =)

@Craigo 2012-03-27 06:26:57

It's not the "proper" way, but IE6/7/8 often just don't play nice when things get a bit complicated, so I totally understand why you would do it this way. You got my up vote.

@NickSoft 2015-09-01 08:51:44

I would do this, but I have to surround every single input box, so that's a lot of extra html.

@Vinay Mehta 2019-06-04 07:35:52

I've a span inside a div and just setting margin: auto to the container div worked for me.

@Shuvo Habib 2016-05-10 20:16:25

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

@Nathaniel Ford 2016-07-11 23:29:33

Do you mind explaining why display:table is better?

@Shuvo Habib 2016-07-12 06:09:33

For display:inline-block, you have to use the negative margin method to fix the extra spacing.

@Ilya Streltsyn 2017-12-08 07:46:31

@NathanielFord, display:table leaves the element in the Block formatting context, so you can control its position with margins etc. as usual. display:-inline-*, on the other hand, puts the element into Inline formatting context, causing the browser to create the anonymous block wrapper around it, containing the line box with the inherited font/line-height settings, and insert the block into that line box (aligning it vertically by baseline by default). This involves more "magic" and therefore potential surprises.

@Harshana 2019-03-26 14:48:36

What if we define a global variable and use that for both.

:root {
    --table-width: 400px;
}

.container{
     width:var(--table-width);
     border: 1px solid black;   // easy visualization
}
.inner-table {
     width:var(--table-width);
     border: 1px solid red;   // easy visualization
}
<div class="container">
    <table class="inner-table">
       <tr>
           <td>abc</td>
       </tr>
    </table>
</div>

@Salman von Abbas 2012-05-12 23:39:02

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.

@uınbɐɥs 2012-07-06 09:22:58

+1 - This is the best, and most clean, solution for modern browsers that also allows the element to be centered. A conditional comment with position: absolute is necessary for < IE8.

@feeela 2012-07-06 15:05:53

Specifying display: inline-block does not add any margins. But CSS handles whitespace to be shown between inline elements.

@HelloWorldNoMore 2016-04-26 22:44:32

Please explain why your solution of display:table works.

@FlorianB 2016-07-02 14:34:53

inline-block makes the element impossible to position in its parent (e.g. if there's a text-align:center you cannot get it to stick to the left) display:table is perfect :)

@m4heshd 2018-05-22 02:40:40

This is the way to go if you have position: absolute

@Alireza 2017-06-17 05:57:07

OK, in many cases you even don't need to do anything as by default div has height and width as auto, but if it's not your case, applying inline-block display gonna work for you... look at the code I create for you and it's do what you looking for:

div {
  display: inline-block;
}
<div>
  <table>
    <tr>
      <td>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi ultrices feugiat massa sed laoreet. Maecenas et magna egestas, facilisis purus quis, vestibulum nibh.</td>
      <td>Nunc auctor aliquam est ac viverra. Sed enim nisi, feugiat sed accumsan eu, convallis eget felis. Pellentesque consequat eu leo nec pharetra. Aenean interdum enim dapibus diam.</td>
      <td>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi ultrices feugiat massa sed laoreet. Maecenas et magna egestas, facilisis purus quis, vestibulum nibh.</td>
    </tr>
  </table>
</div>

@youngrrrr 2018-06-08 00:04:24

This has been mentioned in comments and is hard to find in one of the answers so:

If you are using display: flex for whatever reason, you can instead use:

div {
    display: inline-flex;
}

This is also widely supported across browsers.

@Denny 2020-01-01 15:31:25

This is what I needed when already using display: flex;

@Hamza 2018-04-21 16:11:32

Just put a style into your CSS file

div { 
    width: fit-content; 
}

@David Rector 2018-05-18 21:13:29

I don't think this is a cross-browser supported option.

@molsson 2018-05-24 20:40:23

Currently doesn't work in Edge: caniuse.com/#search=fit-content

@Benj 2019-06-01 08:16:46

You can use -moz-fit-content for FF, presumably the other vendor prefixes will allow their own...

@mfluehr 2019-09-20 15:11:43

This is the same as Vitalii Fedorenko's answer

@ZhenyaUsenko 2018-07-29 22:18:23

You could use display: flex for parent element

#parentElement {
   display: flex;
   flex-direction: column;
   align-items: flex-start;
 }

@RPichioli 2016-10-14 16:00:28

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/

@Chazy Chaz 2017-08-11 19:23:30

What are you talking about? Mozilla Firefox supports inline-block since 3.0 (2008). Source: developer.mozilla.org/en-US/docs/Web/CSS/…

@James 2017-06-21 20:48:46

Try display: inline-block;. For it to be cross browser compatible please use the below css code.

div {
  display: inline-block;
  display:-moz-inline-stack;
  zoom:1;
  *display:inline;
  border-style: solid;
  border-color: #0000ff;
}
<div>
  <table>
    <tr>
      <td>Column1</td>
      <td>Column2</td>
      <td>Column3</td>
    </tr>
  </table>
</div>

@user473598 2010-10-12 16:47:57

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

@miahelf 2011-11-17 08:23:00

@leif81 You can use a span or a div or ul or anything else, the important part is for the container you would like to be minimum width have the CSS property display: inline-block

@Johncl 2011-12-22 13:58:02

Visual Studio 2010 design view does not render this correctly even if the containing elements have "display:block;float:left;" - they will all show vertically with the div width equal to widest element inside. But the browsers all show this correctly (even IE).

@bernstein 2012-02-15 23:09:40

if someone wonders : one can then center the parent of the table by setting "text-align:center" on it's parent and "text-align:left" on it (e.g. <body style="text-align:center"><span style="text-align:left; display:inline-block;"><table>...</table></span></body>)

@David 'the bald ginger' 2012-05-31 10:05:40

@miahelf It does not seem to work with <div>, only with <span>. And this is on code used in IE8 and FF 12. Are <div> browser specific?

@albanx 2012-07-07 20:07:07

It does not work on chrome for me with span, but works using white-space: nowrap;

@streetlight 2013-05-28 19:37:56

This seems to still enable wrapping in Firefox. Does anyone else experience this issue? I have a span with inline-block with 100% width, then two elements inside it, one floated left, the other right. Anyone have a solution? It's driving me crazy!

@Savas Vedova 2014-04-09 12:09:33

Please make note that once you have display: inline-block property set the margin: 0 auto; won't work as expected. In that case if the parent container has text-align: center; then the inline-block element will be horizontally centered.

@Anderson 2014-11-05 09:03:31

@user473598: This does not work. The content is overflowed pas the width of the div.

@Costa 2015-10-09 19:59:41

What if you still need the linebreak after the element? inline-block removes this.

@mareoraft 2015-10-24 19:12:11

inline-block did NOT work for me, but inline-flex DID.

@Exel Gamboa 2016-01-21 16:12:59

If you are using Twitter Bootstrap (tested in 3.0) and "you want to center something within .row, you can use the .offset* classes in the grid system to indent a column by some n number of columns." If this break the design, adjust the margins and padding of the content. Reference: github.com/twbs/bootstrap/issues/399

@HelloWorldNoMore 2016-04-26 22:42:53

Please explain why your solution of inline-block works.

@Hele 2018-06-07 18:59:34

This doesn't work if the contents of the div overflow to the next line.

@Jony 2019-07-03 06:18:39

{ margin: 0 auto; max-width: 960px; display: table; } works for me

@Jaimin Dave 2017-02-22 11:04:51

<div class="parentDiv" style="display:inline-block">
    // HTML elements
</div>

This will make parent div width same as the largest element width.

@Gobliins 2018-02-22 10:15:39

is there a way i can apply this only for vertical size to minimize and keep horizontal large?

@user6558785 2016-07-14 19:33:56

My CSS3 flexbox solution in two flavors: The one on top behaves like a span and the one at the bottom behaves like a div, taking all the width with the help of a wrapper. Their classes are "top", "bottom" and "bottomwrapper" respectively.

body {
    font-family: sans-serif;
}
.top {
    display: -webkit-inline-flex;
    display: inline-flex;
}
.top, .bottom {
    background-color: #3F3;
    border: 2px solid #FA6;
}
/* bottomwrapper will take the rest of the width */
.bottomwrapper {
    display: -webkit-flex;
    display: flex;
}
table {
    border-collapse: collapse;
}
table, th, td {
    width: 280px;
    border: 1px solid #666;
}
th {
    background-color: #282;
    color: #FFF;
}
td {
    color: #444;
}
th, td {
    padding: 0 4px 0 4px;
}
Is this
<div class="top">
	<table>
        <tr>
            <th>OS</th>
            <th>Version</th> 
        </tr>
        <tr>
            <td>OpenBSD</td>
            <td>5.7</td> 
        </tr>
        <tr>
            <td>Windows</td>
            <td>Please upgrade to 10!</td> 
        </tr>
    </table>
</div>
what you are looking for?
<br>
Or may be...
<div class="bottomwrapper">
    <div class="bottom">
    	<table>
            <tr>
                <th>OS</th>
                <th>Version</th> 
            </tr>
            <tr>
                <td>OpenBSD</td>
                <td>5.7</td> 
            </tr>
            <tr>
                <td>Windows</td>
                <td>Please upgrade to 10!</td> 
            </tr>
        </table>
    </div>
</div>
this is what you are looking for.

@Horacio 2017-11-24 03:06:31

kudos for display: inline-flex;. BTW this works without prefix for Chrome 62, firefox 57, and safari 11

@AJchandu 2016-12-06 19:36:51

div{
  width:auto;
  height:auto;
}

@quotesBro 2018-02-13 10:15:39

This will not work if div contains inline (or inline-block) elements and they have different font-size and line-height than the div itself.

@NathanielSantley 2016-10-21 17:22:09

I would just set padding: -whateverYouWantpx;

@Heretic Monkey 2016-10-21 22:00:44

Welcome to Stack Overflow! Please add some explanation of why this code helps the OP. This will help provide an answer future viewers can learn from. See How to Answer for more information.

@NathanielSantley 2016-10-22 16:32:18

It would take away some size of the box so he could make the box "not larger than its contents."

@David Rector 2016-11-16 23:06:32

Isn't negative padding invalid CSS?

@NathanielSantley 2016-11-18 21:44:46

Far from it. In fact I've used it many times and it's perfectly legal.

@Hamed Momeni 2012-06-06 09:54:56

Tampering around with Firebug I found the property value -moz-fit-content which exactly does what the OP wanted and could be used as follow:

width: -moz-fit-content;

Although it only works on Firefox, I couldn't find any equivalent for other browsers such as Chrome.

@Gavin 2017-01-11 22:30:00

As of January 2017, IE (all versions, Edge and mobile included) and Opera Mini have no support for fit-content. Firefox supports width only. Other browsers support it well.

@Ogdila 2014-09-29 06:08:24

Revised (works if you have multiple children): You can use jQuery (Look at the JSFiddle link)

var d= $('div');
var w;


d.children().each(function(){
 w = w + $(this).outerWidth();
 d.css('width', w + 'px')
});

Do not forget to include the jQuery...

See the JSfiddle here

@Mark Amery 2016-09-28 17:32:36

This is broken if your div has multiple children; it simply sets the div width to that of the first child.

@Ogdila 2016-09-30 13:08:41

@MarkAmery First of all, before you give it a negative vote, please read the question carefully, they asked for one child. If you are really curious how it can be done with multiple children see the revised answer.

@Novice 2016-09-30 05:00:55

We can use any of the two ways on the div element:

display: table;

or,

display: inline-block; 

I prefer to use display: table;, because it handles, all extra spaces on its own. While display: inline-block needs some extra space fixing.

@Zeke 2016-06-23 19:20:12

Simply

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

@Abrar Jahin 2016-03-23 09:45:09

An working demo is here-

.floating-box {
    display:-moz-inline-stack;
    display: inline-block;

    width: fit-content; 
    height: fit-content;

    width: 150px;
    height: 75px;
    margin: 10px;
    border: 3px solid #73AD21;  
}
<h2>The Way is using inline-block</h2>

Supporting elements are also added in CSS.

<div>
   <div class="floating-box">Floating box</div>
   <div class="floating-box">Floating box</div>
   <div class="floating-box">Floating box</div>
   <div class="floating-box">Floating box</div>
   <div class="floating-box">Floating box</div>
   <div class="floating-box">Floating box</div>
   <div class="floating-box">Floating box</div>
   <div class="floating-box">Floating box</div>
</div>

@cregox 2015-11-04 03:24:41

If you have containers breaking lines, after hours looking for a good CSS solution and finding none, I now use jQuery instead:

$('button').click(function(){

  $('nav ul').each(function(){
    
    $parent = $(this).parent();
    
    $parent.width( $(this).width() );
    
  });
});
nav {
  display: inline-block;
  text-align: left; /* doesn't do anything, unlike some might guess */
}
ul {
  display: inline;
}

/* needed style */
ul {
  padding: 0;
}
body {
  width: 420px;
}

/* just style */
body {
  background: #ddd;
  margin: 1em auto;
}
button {
  display: block;
}
nav {
  background: #bbb;
  margin: 1rem auto;
  padding: 0.5rem;
}
li {
  display: inline-block;
  width: 40px;
  height: 20px;
  border: solid thin #777;
  margin: 4px;
  background: #999;
  text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button>fix</button>

<nav>
  <ul>
    <li>3</li>
    <li>.</li>
    <li>1</li>
    <li>4</li>
  </ul>
</nav>

<nav>
  <ul>
    <li>3</li>
    <li>.</li>
    <li>1</li>
    <li>4</li>
    <li>1</li>
    <li>5</li>
    <li>9</li>
    <li>2</li>
    <li>6</li>
    <li>5</li>
    <li>3</li>
    <li>5</li>
  </ul>
</nav>

@Mark Amery 2016-09-28 17:29:52

This is visibly broken in the snippet for me in Chrome; clicking the fix button a second time produces different results to clicking it the first time.

@cregox 2016-09-28 19:17:41

@MarkAmery on my mac I just tried it on chrome, safari and firefox and it's all fine: no visible errors, nothing on the console, consistent behavior. maybe it's something with windows...

@Nicolas Talichet 2015-05-24 15:32:56

Personnaly, I simply do this :

HTML code:

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

CSS code:

div {
    display: inline;
}

If you apply a float on your div, it works too but obviously, you need to apply a "clear both" CSS rules at the next HTML element.

@miksiii 2014-10-05 09:36:06

You can do it simply by using display: inline; (or white-space: nowrap;).

I hope you find this useful.

@Sony Santos 2012-01-11 12:01:10

What works for me is:

display: table;

in the div. (Tested on Firefox and Google Chrome).

@Zsolt Szatmari 2014-07-03 13:12:45

Yeah, especially if you need to center with margin: auto. That case inline-block is not the solution.

@Ruslan Stelmachenko 2016-05-20 17:38:04

Also note, that if you want padding work inside this element, you must set border-collapse: separate; style. It's default in many browsers but often css frameworks like bootstrap resetting it value to collapse.

@Silas S. Brown 2017-07-10 16:56:28

Tested on MSIE 6 on a Windows Mobile 6.5 phone made in 2009: it gracefully degrades to a full-width div (which is unlikely to be an issue on a phone). If anyone's using a version of Internet Explorer less than 8 on a desktop, they're using an unsupported operating system (IE6 came with XP, IE7 came with Vista); I'd redirect them to a page telling them to upgrade to GNU/Linux if they want continued safe use of the Internet on that machine.

@trojan 2013-12-11 13:07:16

The answer for your question lays in the future my friend ...

namely "intrinsic" is coming with the latest CSS3 update

width: intrinsic;

unfortunately IE is behind with it so it doesn't support it yet

More about it: CSS Intrinsic & Extrinsic Sizing Module Level 3 and Can I Use?: Intrinsic & Extrinsic Sizing.

For now you have to be satisfied with <span> or <div> set to

display: inline-block;

@maryisdead 2015-05-20 09:36:29

intrinsic as a value is non-standard. It actually is width: max-content. See the MDN page on that or the already linked draft.

@UnLoCo 2013-03-07 17:37:59

I tried div.classname{display:table-cell;} and it worked!

@Vitalii Fedorenko 2013-05-27 00:41:54

You can try fit-content (CSS3):

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

@DAVIDBALAS1 2016-05-09 06:10:20

@BartlomiejSkwira Any substitute working in IE or Eclipse? other solution as inline-block not working to me..\

@Sava B. 2018-03-06 17:33:32

This makes too much sense, of course it lacks support.

Related Questions

Sponsored Content

104 Answered Questions

[SOLVED] How to horizontally center a <div>?

16 Answered Questions

[SOLVED] How do I modify the URL without reloading the page?

28 Answered Questions

[SOLVED] How do I give text or an image a transparent background using CSS?

  • 2009-04-30 09:00:02
  • Stijn Sanders
  • 1515298 View
  • 2236 Score
  • 28 Answer
  • Tags:   html css opacity

33 Answered Questions

[SOLVED] How to make a div 100% height of the browser window

  • 2009-10-15 21:18:43
  • mike
  • 1898525 View
  • 2055 Score
  • 33 Answer
  • Tags:   html css height

14 Answered Questions

[SOLVED] How to move an element into another element?

  • 2009-08-14 20:14:45
  • Mark Richman
  • 1068133 View
  • 1634 Score
  • 14 Answer
  • Tags:   javascript jquery html

13 Answered Questions

[SOLVED] How can I select an element by name with jQuery?

31 Answered Questions

[SOLVED] Make a div fill the height of the remaining screen space

  • 2008-09-18 05:06:17
  • Vincent McNabb
  • 937477 View
  • 1793 Score
  • 31 Answer
  • Tags:   html css html-table

25 Answered Questions

[SOLVED] How to align content of a div to the bottom

Sponsored Content