Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I animate size change from unknown width to 100%?

I have the following situation:
I’m displaying multiple div boxes, each with differing width depending on the context.
For example:

.demand-2 {
    width: 29%;
}
.demand-3 {
    width: 43%;
}

A div with demand-2 is supposed to only be 29% of its parent width.

Now, there’s a button that increases all the boxes to a width of 100%. With the following CSS I make sure that the transition is smooth:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

maxLevelOff {
    animation-duration: 1s;
    animation-name: maxOff;
    animation-fill-mode: forwards;
}
@keyframes maxOff {
    from {
        width: 29;
    }
    to {
        width: 100%;
    }
}

This works perfectly fine, however, as you can see, only for demand-2 since I had to hard code it.

My question now, is there a way I can do this dynamically? Otherwise I’d have to create an animation for all the different widths and that seems tedious.
This should also go the other way. In other words, if I click the button again, all the boxes should transit from 100% back to their original size.

>Solution :

As an alternative, you can use css transitions as well. When the width changes, it smoothly transitions to that new width. You just need to add a class of .full-width to each .demand that you want to be of 100% width.

I provided a simple demo below. If you click on the button once, the widths expand and it returns to the original width if you click it a second time.

let button = document.querySelector('button');

button.addEventListener('click', () => {
  let demand = document.querySelectorAll('.demand');
  demand.forEach(el => {
    if(el.classList.contains('full-width')) el.classList.remove('full-width')
    else el.classList.add('full-width')
  });
});
.demand {
  height: 100px;
  transition: width 0.3s ease-in;
}

.demand-2 {
  background: blue;
  width: 29%;
}

.demand-3 {
  background: red;
  width: 49%;
}

.demand-4 {
  background: green;
  width: 69%;
}

.demand.full-width {
  width: 100%;
}
<div class="demand demand-2"></div>
<div class="demand demand-3"></div>
<div class="demand demand-4"></div>
<button>Click</button>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading