Stephane Savona
Stephane Savona

Reputation: 23

Transition doesn't work on pseudo-element

I want use transition effect in CSS3 but the effect doesn't work. I think I probably made a mistake but I don't see where it is.

On hover, I want make a border with transition in pseudo-element before. I make a codepen : http://codepen.io/Tef/pen/JYBMgR

<div class="container wrap">
<div class="row">
    <div class="box">
        <a href="#">
            <img src="http://placehold.it/90x90/000000" alt="" />
        </a>
    </div>
</div>
</div>

.wrap {
  margin-top: 50px;
}
.wrap a {
  position: relative;
  display: inline-block;
  -webkit-transition: all 1s;
  -moz-transition: all 1s;
  -o-transition: all 1s;
  -ms-transition: all 1s;
  transition: all 1s;
}
.wrap a:hover:before {
  content: '';
  border: 7px solid #ffffff;
  opacity: .7;
  width: 90px;
  height: 90px;
  position: absolute;
  left: 0;
  top: 0;
}

Upvotes: 0

Views: 1365

Answers (2)

Cedric Reichenbach
Cedric Reichenbach

Reputation: 9319

There are a few issues in your code:

  1. :before only exists on :hover, but it should always be there in order to show an animation.
  2. transition is defined on a, but should actually be on a:before (which is conceptually a different DOM element).
  3. There is no initial state of the border, so transition on hover will just start at defaults, and transition backwards on un-hover won't work. To solve this, just add an initial border state like 0px solid transparent.

Here's your fixed example: http://codepen.io/anon/pen/wKxmvB

Upvotes: 1

leuquim
leuquim

Reputation: 655

Two main issues here. First, you're adding a transition the the anchor element, not it's "::before" pseudo-element. Secondly, you're setting no inital state for the pseudo-element, you're setting everything on hover. If you want to transition you need an initial state and an end state. For example:

.wrap {
    margin-top: 50px;
    a {
        position: relative;
        display: inline-block;

        &::before{
            -webkit-transition: all 1s;
            -moz-transition: all 1s;
            -o-transition: all 1s;
            -ms-transition: all 1s;
            transition: all 1s;
            content: '';
            border: 0 solid #ffffff;
            opacity: 0;
            width: 90px;
            height: 90px;
            position: absolute;
            left: 0;
            top: 0;
        }

        &:hover {
            &::before {
                border: 7px solid #ffffff;
                opacity: .7;
            }
        }

    }
}

Notice the transition is on the pseudo element, and I've set the initial values for the inital state for this element (opacity: 0 + border: 0)

Upvotes: 0

Related Questions