So I have used CSS transitions before but I have a unique case with this one. I am writing a custom plugin for creating modals. Essentially I create a div on the fly document.createElement('div') and append it to the body with a few classes. These classes define color and opacity. I would like to use strictly CSS to be able to fade in this div, but making the state change seems difficult b/c they require some user interaction.

Tried some advanced selectors hoping it would case a state change, tried media query hoping to change state...looking for any ideas and suggestions, I really want to keep this in CSS if possible

2

4 Answers

CSS Keyframes support is pretty good these days:

.fade-in { opacity: 1; animation-name: fadeInOpacity; animation-iteration-count: 1; animation-timing-function: ease-in; animation-duration: 2s; } @keyframes fadeInOpacity { 0% { opacity: 0; } 100% { opacity: 1; } }
<h1>Fade Me Down Scotty</h1>
6

OK, first of all I'm not sure how it works when you create a div using (document.createElement('div')), so I might be wrong now, but wouldn't it be possible to use the :target pseudo class selector for this?

If you look at the code below, you can se I've used a link to target the div, but in your case it might be possible to target #new from the script instead and that way make the div fade in without user interaction, or am I thinking wrong?

Here's the code for my example:

HTML

<a href="#new">Click</a> <div> Fade in ... </div> 

CSS

#new { width: 100px; height: 100px; border: 1px solid #000000; opacity: 0; } #new:target { -webkit-transition: opacity 2.0s ease-in; -moz-transition: opacity 2.0s ease-in; -o-transition: opacity 2.0s ease-in; opacity: 1; } 

... and here's a jsFiddle

3

I believe you could addClass to the element. But either way you'd have to use Jquery or reg JS

div { opacity:0; transition:opacity 1s linear;* } div.SomeClass { opacity:1; } 

I always prefer to use mixins for small CSS classes like fade in / out incase you want to use them in more than one class.

@mixin fade-in { opacity: 1; animation-name: fadeInOpacity; animation-iteration-count: 1; animation-timing-function: ease-in; animation-duration: 2s; } @keyframes fadeInOpacity { 0% { opacity: 0; } 100% { opacity: 1; } } 

and if you don't want to use mixins, you can create a normal class .fade-in.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy