htmlcssflexbox

Flexbox and max-width? Parent width is max-width when child is less wide


.row {
    display: flex;
    align-items: center; /* Centers items vertically */
    background-color: yellow;
    height: 100vh;
}

.column {
    max-width: 400px;
  background-color: red;
  flex-grow: 1;
}
<div class="row">
        <div class="column">Text</div>
</div>

Inside a flex box element I have a div with a max-width. Inside the div will be headings. Some headings are long, some short. Even with short headings I want the div to expand to the max-width (not shrink to the width of the child element). Is this possible without using breakpoints?

I've tried various combinations of max-width combined with width and min-width, but can't get it to work

.row {
  display: flex;
  align-items: center
}

.column {
  max-width: 90rem;
  background-colour: red;
}



<div class="row">
  <div class="wrapper">
    <div class="column">Text</div>
  </div>
</div>

Solution

  • You have to maintain the hierarchy while targeting the child element.

    .row {
        display: flex;
      flex-wrap: wrap;
        align-items: center; /* Centers items vertically */
        background-color: yellow;
        height: 100vh;
    }
    
    .wrapper {
      width: 100%;
    }
    
    .column {
        max-width: 400px;
        width: 100%;
        background-color: red;
    }
    <div class="row">
        <div class="wrapper">
            <div class="column">Text</div>
        </div>
    </div>

    Also, flex-grow: 1 will result in same output.