忽略用于计算 CSS 弹性布局中宽度的元素



有没有办法通过CSS告诉浏览器在计算父元素的宽度时忽略某个元素?具体来说,在弹性布局中?

例如,这看起来不错:

<div style="display: inline-flex; flex-direction: column; background-color: #ccc; padding: 1rem">
<h1>Width set by heading</h1>
<div style="border: 1px solid red; padding: 0.5rem; background-color: #fff; color: red">short text</div>
<label>Email</label>
<input type="text" />
<button type="button" style="align-self: center">Submit</button>
</div>

但是,当红色区域增长到大于标题的宽度时,整个<div>的宽度将扩展:

<div style="display: inline-flex; flex-direction: column; background-color: #ccc; padding: 1rem">
<h1>Width set by heading</h1>
<div style="border: 1px solid red; padding: 0.5rem; background-color: #fff; color: red">This text is much longer and causes the width of the div to expand.</div>
<label>Email</label>
<input type="text" />
<button type="button" style="align-self: center">Submit</button>
</div>

有没有办法告诉浏览器使红色区域延伸到父级的宽度上,但在计算必要的宽度时忽略它自己的宽度?像这样的东西,但没有所有的手动<br>标签,或者强制使用特定的宽度:

<div style="display: inline-flex; flex-direction: column; background-color: #ccc; padding: 1rem">
<h1>Width set by heading</h1>
<div style="border: 1px solid red; padding: 0.5rem; background-color: #fff; color: red">This text is much longer but is contained<br />within the parent width.</div>
<label>Email</label>
<input type="text" />
<button type="button" style="align-self: center">Submit</button>
</div>

不是弹性框,但还有另一个选项宽度display:table

.parent {
display: table;
width: 1%;
}
h1 {
white-space: nowrap;
}
<div class="parent" style="background-color: #ccc; padding: 1rem">
<h1>Width set by heading</h1>
<div style="border: 1px solid red; padding: 0.5rem; background-color: #fff; color: red">This text is much longer but is contained within the parent width.</div>
<label>Email</label>
<input type="text" />
<button type="button">Submit</button>
</div>

最新更新