CSS3 transition only when class is added, not when removed

If you want to only apply a transition when the .message element does not have the unreadMessage class, then put the transition properties in the .message:not(.unreadMessage) selector:

.message{
    background-color: red;
}
.message:not(.unreadMessage) {
    -webkit-transition: background-color 5s; /* Safari */
    transition: background-color 5s;
    -webkit-transition-delay: 2s; /* Safari */
    transition-delay: 2s;
}

.unreadMessage{
    background-color: blue;
}
  • Demo: http://jsfiddle.net/Hs8fa/
  • Documentation for :not()

There are two things to remember when using CSS transitions:

  1. Transitions happen when an element's state is modified "using pseudo-classes like :hover or :active or dynamically set using JavaScript."
  2. You have to have a starting point and an ending point or they won't work.

The biggest issue with OP's question isn't their CSS, it's their naming structure. A major pattern of CSS transitions is to modify an element's class (or in the MDN's language "dynamically set using Javascript"). In OP's example they're not modifying an element's class structure, they're changing classes. CSS transitions won't work when an element changes from one class to another, but they will work when a class is added or taken away.

The easiest example of this is going from .element to .element.active. If we put the transition on the base class, .element, and then add a modifying class, .active, the transitions applied to .element will transition from .element settings to .element.active. settings.

Here's a JSFiddle example of modifying a base class

Secondly, and this is one I forget all the time, the base class must have a starting style. I can't transition left in the modified state if I don't have left set in the base state.