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

A CSS2 compatible solution is to use:

.my-div
{
    min-width: 100px;
}

You can also float your div which will force it as small as possible, but you'll need to use a clearfix if anything inside your div is floating:

.my-div
{
    float: left;
}
查看更多
萌妹纸的霸气范
3楼-- · 2018-12-31 04:13

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

查看更多
公子世无双
4楼-- · 2018-12-31 04:15

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;
查看更多
弹指情弦暗扣
5楼-- · 2018-12-31 04:16
<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. =)

查看更多
梦醉为红颜
6楼-- · 2018-12-31 04:16

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.

查看更多
旧人旧事旧时光
7楼-- · 2018-12-31 04:17

You can try fit-content (CSS3):

div {
  width: fit-content; 
  /* To adjust the height as well */ 
  height: fit-content;
}
查看更多
登录 后发表回答