Sam
Sam

Reputation: 6552

Apply CSS properties when transition ends

How do I have the properties of a declaration apply to an element after the CSS3 transitions end? I have something like:

.something {
  background: blue;
  padding: 10px 0px;
  background-clip: content-box;
  transition: box-shadow 300ms;
}
.something:hover {
  box-shadow: 0px 0px 3px blue;
  padding: 0px;
  margin: 10px 0px;
}

I'd like the padding and margin properties in the :hover declaration to be applied after the transition is done in 300ms.

Upvotes: 43

Views: 35154

Answers (3)

Duncan Beattie
Duncan Beattie

Reputation: 2366

you can add a delay like this:

transition: box-shadow 300ms, padding 300ms 400ms;

The box-shadow transition will start on hover and last 300ms, and the padding will start after 400ms and again last 300ms.

.something {
  background: blue;
  color: white;
  padding: 0px;
  background-clip: context-box;
  transition: box-shadow 300ms, padding 300ms 400ms;
}

.something:hover {
  box-shadow: 0px 0px 3px blue;
  padding: 10px;
  margin: 10px 0px;
}
<div class='something'>Something</div>

Article on CSS-Tricks

Upvotes: 35

Manfred Schmitt
Manfred Schmitt

Reputation: 41

When using @Duncan Beattie´s solution one property will override the other. This should work:

transition: box-shadow 300ms linear, padding 300ms linear 400ms;

Syntax:

transition: [property] [duration] [timing-function] [delay], ... more property-transitions

Upvotes: 4

konradstrack
konradstrack

Reputation: 3002

You can achieve this by placing another element inside or outside .something and applying padding and margin transitions to the new element, but with transition-delay value set to the time equal or greater than time of your initial box-shadow transition.

So, for instance:

<div class="immediate">
    <div class="later">
        I can haz transitions.
    </div>
</div>

And CSS:

.immediate {
  background: #eeb;
  transition: box-shadow 300ms;
}

.immediate:hover {
  box-shadow: 0 0 3px black;
}

.later {
   margin: 0;
   padding: 10px 0;
   transition: all 400ms;
   transition-delay: 300ms;
}

.later:hover {
   margin: 10px 0;
   padding: 0;
}

This will perform the box-shadow transition in 300ms, and afterwards margin and padding in 400ms (you can set this transition time to 0 if that's the effect you're looking for).

You can try it on jsFiddle: http://jsfiddle.net/gTVVk/2/

EDIT: Duncan Beattie's answer will do just fine, unless you need to perform different transitions on the same property. Otherwise there's no point to overcomplicate things with nested divs.

Upvotes: 4

Related Questions