How to set div width to the width of the table in it?

12,806

Solution 1

In your case you can also do in the div:

display: table;

Here's the jsFiddle: http://jsfiddle.net/leniel/Et3t5/


Here's another jsFiddle that shows you a similar case: http://jsfiddle.net/leniel/T7DTc/

If the div's width: auto; then it expands to accommodate the textarea inside the table. If you set it to width: 500px; then the textarea grows outside the div.

So the solution looks like setting width: auto;. Of course something special in your code may be interfering.

Solution 2

Setting table { width:100% } solved it. Now I can keep the div big enough and the table just fits in it. Thanks.

Solution 3

Make the div containing the table inline-block. I.e. display: inline-block. This will force it to render inline while being block. Alternatively display: table will work too.

Link to a jsFiddle: http://jsfiddle.net/Mr9jQ/

Share:
12,806
Loolooii
Author by

Loolooii

Full-stack developer. Love Flutter, Vue and React.

Updated on June 04, 2022

Comments

  • Loolooii
    Loolooii almost 2 years

    I have a div, which contains a table. Everything is working as I want, except I don't know how to set the width of the div so that it grows as the width of the table inside it grows. How Can I do that? Thanks.

    This is the CSS code of the div:

    #events-table-wrapper {
        margin-left: auto;
        margin-right: auto;
        width: 500px;
        margin-top: 100px;
        border: 1px solid #CCC;
        border-radius: 4px;
        -moz-border-radius: 4px;
        -webkit-border-radius: 4px;
    }
    

    Setting width to auto didn't help. Btw, I didn't change anything in the table in CSS.

    Edit: Here is a live version: http://jsfiddle.net/ZDF2U/

  • Loolooii
    Loolooii over 11 years
    In that case the div has the width of the whole page.
  • Loolooii
    Loolooii over 11 years
    Very nice solution. Better than setting table width to 100%. Thank!
  • Loolooii
    Loolooii over 11 years
    Leniel's solution is better. This one still requires you to mess with the width of the div.