Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display:none Removing Pseudo-elements

Hi I was answer this question and I notice an strange behavior

The Context

I have an HTML structure like this:

<div class="btn">
    Click me
</div>
<div class="element">
    Div Box With Pseudo Element
</div>

And CSS Just the relevant

.element {
    display:none;
}
.element:after {
    content:" ";
    display:block;
    width:0;
    background:black;
    transition:6s ease;
}
.element.clicked:after {
    width:100%;
}

Where the element needs to be display:none and need to be show/hide when click the btn element. That works fine with Jquery and fadeToggle.

Also I add a class to animate a pseudo-element with transition and width. Need to animate at the same time of the fade on the parent.

The problem

If you see this FIDDLE, you can notice at first click the expected behavior is the pseudo-element grows form 0 to 100% but instead is 100% without grow.

If you click again then it's fine changing from 100% to 0

Question

I notice whit the inspector that setting display:none to the element makes the pseudo-element disappear.

enter image description here

This causes the element can't be from 0 to 100% since doesn't exist.

Anyone Knows How to stop that behavior or how to avoid the non-render of the element. I was wonder about the form pseudo-elements were rendered and If they need a Visible parent

This issue doesn't happen with visibiliy or opacity just with display

like image 271
DaniP Avatar asked Oct 19 '22 23:10

DaniP


1 Answers

I believe this issue lies in the fact of how CSS transition works. As you well know a css transiton is applied when an element has a property changed from one value to another.

But in your scenario, the property isn't in fact changing. A pseudo element does not exists while its parent is in the display: none property. So when you call the fadeToggle(), the element becomes display: block and then pseudo is created.

But immediately it is already affected by the .clicked class of the parent, which gives the pseudo a width: 100% property.

So, essencially, the width property is never changed. It goes from "non existent" to "100%", therefore, no transition is applied.

EDIT

So, what you really need is to revert the order of the apply of .clicked class to after the fade started:

Updated Fiddle

$('.element').stop().fadeToggle(3000).toggleClass('clicked');
like image 137
LcSalazar Avatar answered Nov 13 '22 16:11

LcSalazar