Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make div width adapt automatically to contents within it

Tags:

html

I have a div within which a table would lie. Now I want this div to have its width set automatically to the width of table within it.

For example:

<div>
  <table>
    <tr>
      <td>Hello</td>
      <td>World</td>
    </tr>
    <tr>
      <td>Sample</td>
      <td>Table</td>
    </tr>
  </table>
</div>

I tried giving float: left; property to it. It works, but then it creates another problem. Whatever content is put after this div gets placed to the right of it in the empty space.

What needs to be done?

like image 876
Shades88 Avatar asked Aug 11 '11 09:08

Shades88


People also ask

How do I make div width auto adjust to content?

One way you can achieve this is setting display: inline-block; on the div . It is by default a block element, which will always fill the width it can fill (unless specifying width of course).

How do I make a div stay the same size?

if you set width:500px; and height:300px; (or whatever size you want) the div should stay the same size. Also, you can set overflow:hidden; so that if whatever is in the div goes beyond those bounds, it is not shown, and does not resize the div. Show activity on this post. Try this one.

How do you make a div expand to fill available space?

The width property is used to fill a div remaining horizontal space using CSS. By setting the width to 100% it takes the whole width available of its parent. Example 1: This example use width property to fill the horizontal space. It set width to 100% to fill it completely.


1 Answers

You are effectively attempting to change the display model of that div element, so you should change it's CSS 'display' property as follows:

div{
    display: inline-block;
}

Here's a jsFiddle demonstrating the solution.

like image 173
Spycho Avatar answered Sep 17 '22 12:09

Spycho