Search code examples
htmlcssflexbox

How to control which inner div will control the width of an outer div


I have the following code, and would like the width of the outer div to be driven by the width of the inner div. Instead, it's driven by the width of the line of text. I want the line of text to wrap instead, with the max width of outer being the width of inner. The number of boxes within inner is dynamic, so I can't use fixed widths (or min/max widths)

.outer {
  padding: 10px;
  background-color: #cdcdcd;
}

.inner {
  padding: 10px;
  background-color: #fff;
  display: flex;
}

.box {
  height: 40px;
  width: 80px;
  background-color: red;
  margin: 10px;
}
<div style="background-color: #fff; padding: 20px; display:flex">
  <div class="outer">
    <div class="inner">
      <div class="box">Box 1</div>
      <div class="box">Box 2</div>
    </div>
    <div>Here is a very long piece of text that is extending the outer too far, when I want the width of outer to be limited by inner, and this sentence to wrap instead</div>
  </div>
</div>


Solution

  • .outer {
      padding: 10px;
      background-color: #cdcdcd;
    }
    
    .inner {
      padding: 10px;
      background-color: #fff;
      display: flex;
    }
    
    .box {
      height: 40px;
      width: 80px;
      background-color: red;
      margin: 10px;
    }
    
    .text {
      width: min-content;
      min-width: 100%;
    }
    <div style="background-color: #fff; padding: 20px; display:flex">
      <div class="outer">
        <div class="inner">
          <div class="box">Box 1</div>
          <div class="box">Box 2</div>
        </div>
        <div class="text">Here is a very long piece of text that is extending the outer too far, when I want the width of outer to be limited by inner, and this sentence to wrap instead</div>
      </div>
    </div>

    This approach works pretty well. min-width is based on the parent width so basically min-width: 100% along with a width value which is the actual minimum width.