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 to have CSS transition apply when width increases, but not when decreasing?

I have an element that is changing width under different scenarios. I have set up CSS with a transition for the width:

.element-class {
    transition: width 500ms ease 0ms;
}

But I only want it to do that transition if the width is decreasing. When it increases, I want it to change immediately (so no transition). Is it possible to tell the transition property to only work in one scenario like that? Or is there another way to do this?

I’ve tried adding two transition properties, but they both don’t apply at the same time (which I expected, but I figured it was worth a shot).

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

>Solution :

You can apply your transition on a class or pseudo element like :hover instead of applying it on your element.

document.getElementById('toggle').addEventListener('click', () => {
  document.getElementById('square').classList.toggle('w-100');
})
#square {
  margin-top: 20px;
  border: 1px solid black;
  width: 50px;
  height: 50px;
}

#square:hover {
  background-color: orange;
  transition: background-color 500ms;
}

#square.w-100 {
  width: 100px;
  transition: width 500ms;
}
<button id="toggle">Toggle</button>
<div id="square"></div>
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