How to make div not larger than its contents?

2018-12-31 03:29发布

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.

标签: html css width
30条回答
梦该遗忘
2楼-- · 2018-12-31 04:24

There are two better solutions

  1. display: inline-block;

    OR

  2. display: table;

Out of these two display:table; is better.

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

查看更多
余生无你
3楼-- · 2018-12-31 04:24

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>

查看更多
情到深处是孤独
4楼-- · 2018-12-31 04:27

Not knowing in what context this will appear, but I believe the CSS-style property float either left or right will have this effect. On the other hand, it'll have other side effects as well, such as allowing text to float around it.

Please correct me if I'm wrong though, I'm not 100% sure, and currently can't test it myself.

查看更多
与风俱净
5楼-- · 2018-12-31 04:27

Just put a style into your CSS file

div { 
    width: fit-content; 
}
查看更多
与风俱净
6楼-- · 2018-12-31 04:31
<div class="parentDiv" style="display:inline-block">
    // HTML elements
</div>

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

查看更多
怪性笑人.
7楼-- · 2018-12-31 04:31

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

查看更多
登录 后发表回答