Home > Software engineering >  The flex-grow property seems not work properly
The flex-grow property seems not work properly

Time:10-27

I have a parent div and two children div under the parent. From my understanding, when I set the first child's flex-grow to zero, the width of this element is never change, but when I add some text to the second child, the width of first child decreased. But why?

document.querySelector('#button').addEventListener('click', function() {
  document.querySelector('.child2').appendChild(document.createTextNode('This is text. '));
})
.parent {
  width: 400px;
  height: 400px;
  background-color: #ccc;
  display: flex;
}

.child1 {
  width: 100px;
  flex-grow: 0;
  background: red;
}
<button id="button">Add text</button>

<div class="parent">
  <div class="child1">fdsafa</div>
  <div class="child2"></div>
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

You are right. flex-grow stops the width from changing if it is expanding. But if it is getting smaller it does not do anything. Thats what flex-shrink is for. Try flex-shrink on the child.

document.querySelector('#button').addEventListener('click', function() {
  document.querySelector('.child2').appendChild(document.createTextNode('This is text. '));
})
.parent {
  width: 400px;
  height: 400px;
  background-color: #ccc;
  display: flex;
}

.child1 {
  width: 100px;
  flex-shrink: 0;
  background: red;
}
<button id="button">Add text</button>

<div class="parent">
  <div class="child1">fdsafa</div>
  <div class="child2"></div>
</div>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related