dxer
dxer

Reputation: 76

CSS transition on a pseudo-element doesn't work for a simple background-color change

I'm trying to apply a transition effect on a div when mouse over using :hover:before in CSS so it could create a dark overlay but unfortunately there's no transition happening. It just colors in and out without fading effect as if no transition is applied.

Here's a fiddle.

I applied transition to every element. I also tried ::before instead of :before and of course added all browser support (I'm using chrome). Tried transition only on background-color won't work either. Please tell me what I'm doing wrong. Thanks in advance.

HTML:

<div class="container">
    <!-- ... -->
</div>

CSS:

.container{
    border: solid 1px #000;
    padding: 50px;
    position: relative;
}

.container:before{
    content: "";
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    display: none;
    transition: all 3s ease;
}

.container:hover:before{
    display: block;
    background-color: rgba(0, 0, 0, 0.2);
}

Upvotes: 0

Views: 1215

Answers (1)

Raphael Aleixo
Raphael Aleixo

Reputation: 607

The problem is that "display" is not transitionable. You can't use any transition if you are moving from display:none to display:block;

.container:before{
    content: "";
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    background-color: rgba(0, 0, 0, 0);
    pointer-events:none; /* So it won't be clickable */
    transition: all 3s ease;
}

.container:hover:before{
    pointer-events: all;
    background-color: rgba(0, 0, 0, 0.2);
}

Upvotes: 1

Related Questions