简体   繁体   中英

How to transition item size change inside a display: flex; justify-content: space-between; div

I have a display: flex; justify-content: space-between; display: flex; justify-content: space-between; container div with 2 chidren inside. The second child classes will be changed to include (or not) a class with display: none; . It does get hidden when the logic applies this class, and the first child grows in width to fit the parent div. The problem is that I can't make the first child width change to transition, so when the second child goes hidden or not, the first child is instantly changing its width. I want its width to grow to its full width, instead of suddenly changing to its full width.

I am using React, but it should be possible only with css, right? If so, how can I achieve this?

Here is the reproducible example:

 document.getElementById("toggle").addEventListener("click",function(e){ document.getElementById("second").classList.toggle("hidden") },false);
 .container { display: flex; justify-content: space-between; background: #aaf; width: 200px; height: 40px; align-items: center; }.container > *:first-child { background: #afa; flex-grow: 1; }.container > *:last-child { display: flex; justify-content: space-between; background: #faa; width: 50px; }.container > *:last-child.hidden { display: none; }
 <div class="container"> <div><span>1st</span></div> <div id="second" class="hidden">2nd</div> </div> <button id="toggle">toggle</button>

In order to transition between widths, you must toggle the width value and use the CSS transition property. You cannot transition the width using hidden , as this is either true or false, there are no intermediate values to transition between.

Changes I made to your code:

  • Add overflow: hidden on the container
  • Toggle between widths (instead of the 'hidden' property). This enables transition to work.
  • Add transition: width 2s to both children.

 document.getElementById("toggle").addEventListener("click",function(e){ const width = document.getElementById("second").style.width; if (width === "" || width === "50px") { document.getElementById("second").style.width = "0px"; } else { document.getElementById("second").style.width = "50px"; } },false);
 .container { display: flex; justify-content: space-between; background: #aaf; width: 200px; height: 40px; align-items: center; overflow: hidden; }.container > *:first-child { background: #afa; width: 100%; transition: width 2s; }.container > *:last-child { background: #faa; width: 50px; transition: width 2s; }
 <div class="container"> <div><span>1st</span></div> <div id="second">2nd</div> </div> <button id="toggle">toggle</button>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM