Make the width of the div automatically adapted to the content inside it

I have a div that will be in. Now I want this div have its width set automatically to the width of the table inside it.

For instance:

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

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

What should be done?

+6
source share
5 answers

You need to clear the float after your div by adding style = "clear: left;" on the following item:

 <div style="float: left;"> <table>...</table> </div> <div style="clear: left;"> ... </div> 
+5
source

In fact, you are trying to change the display model of this div element, so you should change its CSS 'display' property as follows:

 div{ display: inline-block; } 

Here jsFiddle demonstrates the solution.

+15
source

You need to clear the float explicitly so as not to damage subsequent elements with float. See the article for more details.

+2
source

This is brand new, but ...

If you do not want the element to become an inline block, you can do this:

 .parent{ width: min-content; } 

You have many other width options. More details here: http://caniuse.com/#search=intrinsic

+1
source

If I understand correctly, you want the div to be as wide as the table, but not wider. Because the div element is a block element, it will always be as wide as possible unless you give it an explicit width. Your choice is to either add a display:inline style or use an inline element, such as a "span".

0
source

Source: https://habr.com/ru/post/894801/


All Articles