user2209644
user2209644

Reputation: 711

display none breaks animation

i want a certain div to be shown in certain circumstances, and i want it to be animated, at the start it should be invisible so...

.fixedNav{
    background-color: rgba(28,20,13, 0.75);
    position:fixed;
    color:white;
    width:60vw;
    margin-top:-50px !important;
    z-index: 1;
    display:none;
    opacity:0;
    transition:opacity .3s ease-in;
}

and then i animate the opacity with css by adding this class, with jquery, to it:

.fixedNavActive{
    display: block;
    opacity:1;
}

and it all works fine if i remove the display: none; from the main class, if i leave it there then the opacity isn't animated, it just appears, why does it break it and how can i make it animate the opacity instead of toggling it to 1?

Upvotes: 6

Views: 2300

Answers (3)

Gray Spectrum
Gray Spectrum

Reputation: 733

Basically, you cannot animate display properties, and even though you're only trying to animate the opacity, that transition fails because when the transition begins, the element doesn't exist. It has been removed from the flow due to the display: none property.

You can achieve the effect you're looking for by using visibility: hidden and visibility: visible, which is an animatable property, and if you need to effectively remove the element from the flow when it lacks visibility, then you can apply a max-height of 1px to the element and a margin-top of -1px.

Upvotes: 6

Ildrid
Ildrid

Reputation: 11

I place the 'display:none;' on the content of the element, or wrap what I want to hide in another div. And then set the transition on the surrounding element. To let the animation fade both in and out you will have to set the height, padding or something to keep it from getting a height of 0 the second the content disappears.

Solves it for me at least :)

.hidden { 
    opacity: 1;
    height:20px;
    transition: all 0.5s linear;
}

.container:hover > .hidden{
   opacity: 0;
   height:0;
   transition: all 0.5s linear;
}

.container:hover > .hidden > .hidden-content{
    display: none;
}
<div class="container">
  <div> Hello! </div> 
  <div class="hidden">
      <div class="hidden-content"> Goodbye! </div>
   </div>  
  <div> Some other text! </div>
</div>

Upvotes: 1

Albzi
Albzi

Reputation: 15609

JSFiddle

display properties can not be animated in CSS.

You can just use opacity:0; and then opacity:1.

To get a better effect you could always use visibility:hidden; for your use.

Upvotes: 0

Related Questions