【问题标题】:Ignore element for calculating width in CSS flex layout [duplicate]忽略用于计算 CSS flex 布局中宽度的元素 [重复]
【发布时间】: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>

但是,当红色区域增长到大于表头的宽度时,整个&lt;div&gt;的宽度就会扩大:

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

有没有办法告诉浏览器让红色区域延伸到父级的宽度,但在计算必要的宽度时忽略它自己的宽度?像这样的东西,但没有所有手动 &lt;br&gt; 标签,或强制指定宽度:

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

【问题讨论】:

    标签: html css flexbox


    【解决方案1】:

    不使用 flexbox,但有另一个选项宽度 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>

    【讨论】:

    • 你确定这会奏效吗?如果您取出文本中的手动&lt;br&gt; 标签,我想您会遇到完全相同的问题。
    • 编辑 - 修复它。
    猜你喜欢
    • 1970-01-01
    • 2016-05-05
    • 2016-09-09
    • 1970-01-01
    • 1970-01-01
    • 2016-05-02
    • 1970-01-01
    • 1970-01-01
    • 2010-09-07
    相关资源
    最近更新 更多