【发布时间】:2019-08-30 22:52:01
【问题描述】:
有没有办法通过 CSS 告诉浏览器在计算父元素的宽度时忽略某个元素?具体来说,在 flex 布局中?
例如,这看起来不错:
<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>
【问题讨论】: