示例jsfiddle:https://jsfiddle.net/ogf6ps39/1/
给出类似的模板:
<div class="outer">
<div class="inner">
hello world testing hello world
</div>
</div>
外部是position: absolute
,如何使子容器的宽度基于其内容。
所以类似:
编辑:
只需添加,内部div的内容是未知的,并且会动态更改。所以我不能使用固定的宽度或宽度百分比。内部div也有可能溢出外部div
通常用于定义相对于元素父级的尺寸对象。
.outer {
position: absolute;
max-width: 100px;
max-height: 300px;
min-height: 100px;
background-color: yellow;
}
.inner {
width: 85%;
background-color: green;
}
<div class="outer">
<div class="inner">
hello world testing hello world
</div>
</div>
.inner
元素是div
,默认情况下是block
元素。这意味着默认情况下,其宽度为父级的100%。您可以将.inner
的显示更改为inline-block
,例如不具有100%的默认宽度,但是问题是里面有文本。一旦该文本至少填满了一行(父级的一个完整宽度),并且需要换行-从那一刻起,该文本便自动被认为需要父级的整个宽度。即使文本在视觉上看起来使用较小的宽度(实际上,实际上并没有使用wull宽度-它只是自动换行)。如果您看一下简短的文字,您可能会明白这一点。我在此处提供inline-block
的示例: .outer {
max-width: 100px;
max-height: 300px;
min-height: 100px;
background-color: yellow;
}
.inner {
background-color: green;
display: inline-block;
margin-bottom: 10px;
}
<div class="outer">
<div class="inner">
hello world testing hello world
</div>
<div class="inner">
hello
</div>
<div class="inner">
hello world
</div>
</div>
与此同时,我可以向您保证的是,父元素上的absolute
位置完全不影响此。
max-content
作为宽度.inner {
width: max-content;
background-color: green;
}