如何使父 div 自动调整到其子 div 的宽度

我试图让父 div 只和子 div 一样宽。自动宽度是使父 div 适合整个屏幕。子 div 将根据其内容的不同而具有不同的宽度,因此我需要父 div 进行相应的调整。

<div style='width:auto;'>
<div style="width: 135px; float: left;">
<h4 style="padding-right: 5px; padding-left: 15px;">Column1</h4>
<dl style="padding-right: 5px; padding-left: 15px; margin-top: -8px; overflow-x: hidden;">
<dd style="white-space: nowrap;">1</dd>
<dd style="white-space: nowrap;">2</dd>
</dl>


<h4 style="padding-right: 5px; padding-left: 15px;">Column1</h4>
<dl style="padding-right: 5px; padding-left: 15px; margin-top: -8px; overflow-x: hidden;">
<dd style="white-space: nowrap;">1</dd>
<dd style="white-space: nowrap;">2</dd>
</dl>
</div>


<div style="width: 135px; float: right;">
<h4 style="padding-right: 5px; padding-left: 10px;">Column2</h4>
<dl style="padding-right: 5px; padding-left: 15px; margin-top: -8px; overflow-x: hidden;">
<dd style="white-space: nowrap;">1</dd>
<dd style="white-space: nowrap;">2</dd>
<dd style="white-space: nowrap;">3</dd>
</dl>
</div>
</div>
198236 次浏览

Your interior <div> elements should likely both be float:left. Divs size to 100% the size of their container width automatically. Try using display:inline-block instead of width:auto on the container div. Or possibly float:left the container and also apply overflow:auto. Depends on what you're after exactly.

The parent div (I assume the outermost div) is display: block and will fill up all available width of its container (in this case, the body) that it can. Using a different display type -- inline-block is probably what you are going for:

http://jsfiddle.net/a78xy/

this is the easiest way to make your parent div inherit it's child width.

.container-fluid {
border: 1px solid black;
/*the needed css class to make your parent div responsive to it's children's max-width
*/
width: max-content
}
.wrapper {
border: 1px solid red;
width: 300px
}
<div class="container-fluid">
<div class="wrapper">xxx</div>
</div>

i hope someone finds this usefull

I was struggling with this and was setting the width of my parent component. As an accident, I found out the CSS width: fit-content;

Here is an example:

.outerContainer {
width: 300px;
height: 300px;
background: gray;
}


.innerContainer {
width: fit-content;
border: 3px solid red;
}


.item {
width: 200px;
height: 200px;
padding: 10px;
background: blue;
}
<div class="outerContainer">
<div class="innerContainer">
<div class="item">
</div>
</div>
</div>

In the example the innerContainer div (the one with a red background) fits to the content of the item container. The outerContainer div is there to show the contrast.