Search code examples
cssflexbox

How to prevent flex child from growing whole column width


I have some elements in a column flexbox which is itself a flex element.

When I press a button the content of my last element is changing it's width and becoming the wider element of the flexbox making it wider. I want to prevent that because it's not pretty. The width must not change when I press the button.

See code snippet for clarification.

var thirdDivs = [...document.querySelectorAll('.child.third')];
document.getElementById('toggleButton').addEventListener('click', function() {
  thirdDivs.map((thirdDiv) => {thirdDiv.classList.toggle('hidden');});
});
main{
  display: flex;
}

.container {
  display: flex;
  flex-flow: column wrap;
  border: 1px solid red
 }
  
 .hidden {
  display: none;
 }
<p> I don't want that red box to change size when I press the button. I want the text to be on two different lines</p>
<button id="toggleButton">Switch</button>
<main>
  <div class='container'>
    <div class='child first'>
    <p>Some content</p>
    </div>
    <div class='child second'>
    <p>Some more content</p>
    </div>
    <div class='child third'>
    <p>A short text</p>
    </div>
    <div class='child third hidden'>
    <p>A very much more longer text<p>
    </div>
  </div>
</main>

I tried to play with flex-grow and flex-shrink without success.


Solution

  • Well, you still have to choose which child you will use to calculate the width of the parent - .second {white-space: nowrap;}. This element needs to prevent line breaks. And the parent should be asked to use the minimum possible width to display the content - width: min-content;

    var thirdDivs = [...document.querySelectorAll('.child.third')];
    document.getElementById('toggleButton').addEventListener('click', function() {
      thirdDivs.map((thirdDiv) => {
        thirdDiv.classList.toggle('hidden');
      });
    });
    main {
      display: flex;
    }
    
    .container {
      display: flex;
      flex-flow: column wrap;
      border: 1px solid red;
      width: min-content;
    }
    
    .second {
      white-space: nowrap;
    }
    
    .hidden {
      display: none;
    }
    <p> I don't want that red box to change size when I press the button. I want the text to be on two different lines</p>
    <button id="toggleButton">Switch</button>
    <main>
      <div class='container'>
        <div class='child first'>
          <p>Some content</p>
        </div>
        <div class='child second'>
          <p>Some more content</p>
        </div>
        <div class='child third'>
          <p>A short text</p>
        </div>
        <div class='child third hidden'>
          <p>A very much more longer text
            <p>
        </div>
      </div>
    </main>