CSS fade-in, instant hide

Asked 8 years, 2 months agoModified todayViewed 14k times
1
I am trying to build a class that I can easily slap onto an element that would fade the element into view when it is rendered but instantly hide it when I set `display` to none. So far, the classes I've build fade the element into view, but there is a slight delay on hiding OR the element fade-hides as well. I have this so far using animations for the class `fadeIn`: ```css @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } } .fadeIn { animation: fadeIn 0.2s both ease-in; } ``` This one fades-in but there is a delay when hiding it Another one looks like this: ```css .fade-show { opacity: 1; transition: opacity 2s ease-in; -moz-transition: opacity 2s ease-in; -webkit-transition: opacity 2s ease-in; } ``` This doesn't actually fade-in and delays on hide. I would just like something to fade when rendered or `display` set to `block` but instantly hide when `display` set to `none`. Usage for this class would be as follows: ```html <div class="fadeIn">I fade in but don't fade on hide</div> ```
htmlcsscss-transitionscss-animationsfadein
yevg
yevg
1986asked Jul 11, 2017 at 0:43

2 Answers

Sorted by:
5
Enjoy :) You have also this library of animations, it's very nice and simply to use! > **Animate.css** > https://daneden.github.io/animate.css/ ```css .fadeMe { animation:fadeIn 1s linear; } @keyframes fadeIn { 0% { opacity:0 } 100% { opacity:1; } } .fadeMe.none { display:none } ``` ```html <div class="fadeMe">Fade in (try to add none after the class?)</div> ```
Nepplot
Nepplot
118answered Jul 11, 2017 at 0:59

Comments

BenOver a year ago

The element remains in the dom if you don't set `display: none;` this will effect layout in flexbox for example.

3
You don't need to use KeyFrames to achieve this. Set the initial `opacity` of the element to `0`. Add a class (".show") to the element which sets the `opacity` to `1` and adds the `transition` attributes. Note, if you were to add the transitions to the `div` CSS selector instead of the ".show" class then it would fade in AND out. Add/remove the ".show" class to show/hide the element. ```css div { opacity: 0; } .show { opacity: 1; transition: opacity 2s ease-in; -moz-transition: opacity 2s ease-in; -webkit-transition: opacity 2s ease-in; } ``` ```html <div class="show">I fade in but don't fade on hide</div> ```
Naeem Akhtar
Naeem Akhtar
1539answered Jul 11, 2017 at 1:05edited 37 mins ago

Your Answer

Community activity
Last 1 hr
15,513 users online
23 questions
21 answers
95 comments
323 upvotes
Popular tags
c++pythonandroidc#java.net
Popular unanswered question
Validating struct with an attribute (proc-macro)
rustrust-proc-macros
freakish56.7k7 hours ago