Skullbox
Skullbox

Reputation: 441

CSS: Fade out only if visible

I wonder if it is possible to solve this with only CSS or SASS. I have a website that has a popup that fades in if the browser window is smaller in width than $min-width pixels and fades out otherwise and stays hidden.

@media screen and (min-width: $min-width) {
    .app-screen {
        -webkit-animation: fade_out 0.5s forwards;
    }
}

@media screen and (max-width: $min-width - 1) {
    .app-screen {
        -webkit-animation: fade_in 0.5s forwards;
    }
}

EDIT: Sorry, forgot to post my animations:

@-webkit-keyframes fade_in {
    0% {
        opacity: 0;
    }
    100% {
        opacity: 1;
    }
}

@-webkit-keyframes fade_out {
    0% {
        opacity: 1;
    }
    100% {
        opacity: 0;
    }
}

The problem is that when users with a big window enter the site the popup appears and fades out. The popup is hidden by default in the css but since the fade out criteria is met, the fade_out animation is started. But I don't want it to start if the popup is already hidden.

Is there some SASS solution like "@if opacity > 0" I can before my fade-out animation or an animation property I've missed?

Upvotes: 1

Views: 1070

Answers (2)

Hendrik Kangro
Hendrik Kangro

Reputation: 113

i propose a very simplistic approach.

.app-screen {
    opacity: 0;
    transition: opacity 0.5s;
}
@media screen and (max-width: $min-width) {
    table {
        opacity: 1;
    }
}

This way if the screen is initially loaded bigger than @min-width nothing will happen, if smaller the screen will fade in. When the screen is dragged bigger or smaller, the screen will accordingly fade in or out.

Cheers

Upvotes: 1

Andrew Myers
Andrew Myers

Reputation: 2786

I would do this with CSS3 transitions instead of animations.

/* Assuming $min-width: 700px; */

.app-screen {
  transition: opacity 0.5s ease-in;
}

@media screen and (min-width: 700px) {
    .app-screen {
        opacity: 0;
    }
}

@media screen and (max-width: 699px) {
    .app-screen {
        opacity: 1;
    }
}
<div class="app-screen">
  <p>You can only see me on small screens.</p>
</div>

Note that the way I have it requires you to use the same easing function to fading in as fading out (some people prefer to have ease-in one way and ease-out the other way).

Upvotes: 4

Related Questions