1

Is there a way to tell the browser, via CSS, to ignore a certain element when calculating the width of a parent element? Specifically, within a flex layout?

For example, this looks fine:

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

However, when the red area grows to a width that is larger than the header, the width of the entire <div> expands:

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

Is there a way to tell the browser to make that red area stretch across the width of the parent, but to ignore its own width when calculating the necessary width? Something like this, but without all the manual <br> tags, or forcing a specific width:

<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>
Dave Mateer
  • 17,608
  • 15
  • 96
  • 149

1 Answers1

0

Not with flexbox but there is another option width 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>
Paulie_D
  • 107,962
  • 13
  • 142
  • 161