Flex child of child does not expand to 100%

Viewed 167

In CSS, if a child of a child is set to width: 100% and the wrapping div has display: flex set, the content does not expand to 100% it only uses the space of the content.

How would one make it expand to the size the grandchild sets itself but still use flex?

flex-grow is probably not the answer since this will always expand to take up the full space and not respect the size the grandchild sets itself.

See following example:

.wrapperFlex, .wrapperBlock{
  border: 1px solid silver;
}

.wrapperFlex {
  display: flex;
}

.levelOne {
}

.levelOneGrow {
  flex-grow: 1;
}

.levelTwo, .levelTwoFullWidth {
  color: white;
  background-color: blue;
}

.levelTwoFullWidth {
  width: 100%;
}

.levelOnePassthrough{
  display: contents;
}
<!-- Premise -->
<div class="wrapperFlex">
  <div>PRE</div>
  <div class="levelOne">
    <div class="levelTwoFullWidth">
      WRAPPER FLEX
    </div>
  </div>
  <div>AFTER</div>
</div>
<br/>

<!-- Not what is wanted, the grandchild here does not actually expand to 100%
it should be only as wide as the content here -->
<div class="wrapperFlex">
  <div>PRE</div>
  <div class="levelOneGrow">
    <div class="levelTwo">
      WRAPPER FLEX GROW
    </div>
  </div>
  <div>AFTER</div>
</div>

<br/>

<!-- What is wanted but not possible, display: contents is not commonly available -->
<div class="wrapperFlex">
  <div>PRE</div>
  <div class="levelOnePassthrough">
    <div class="levelTwoFullWidth ">
      WRAPPER FLEX PASSTHROUGH
    </div>
  </div>
  <div>AFTER</div>
</div>

3 Answers

Can you set flex-basis to the child?

.wrapperFlex, .wrapperBlock{
  border: 1px solid silver;
}

.wrapperFlex {
  display: flex;
}

.wrapperBlock {
  display: block;
}

.levelOne {
  flex-basis: 100%; /* Set flex-basis to 100% */
}

.levelTwo {
  color: white;
  width: 100%;
  background-color: blue;
}
<div class="wrapperFlex">
  <div class="levelOne">
    <div class="levelTwo">
      WRAPPER FLEX
    </div>
  </div>
</div>

<br/>

<div class="wrapperBlock">
  <div class="levelOne">
    <div class="levelTwo">
      WRAPPER BLOCK
    </div>
  </div>
</div>

set .levelOne {width:100%} ,if im not misunderstanding you.

You need to add the flex property as one to the child i.e levelOne like this flex:1;. It will work properly as you check here.

.wrapperFlex, .wrapperBlock{
  border: 1px solid silver;
}

.wrapperFlex {
  display: flex;
}

.wrapperBlock {
  display: block;
}

.levelOne {
flex:1;
}

.levelTwo {
  color: white;
  width: 100%;
  background-color: blue;
}
<div class="wrapperFlex">
  <div class="levelOne">
    <div class="levelTwo">
      WRAPPER FLEX
    </div>
  </div>
</div>

<br/>

<div class="wrapperBlock">
  <div class="levelOne">
    <div class="levelTwo">
      WRAPPER BLOCK
    </div>
  </div>
</div>

Related