Search code examples
csscss-transitions

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).


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>