CSS How To Make An Element Fade In And Then Fade Out?


Answer :

Use css @keyframes

.elementToFadeInAndOut {    opacity: 1;    animation: fade 2s linear;}@keyframes fade {  0%,100% { opacity: 0 }  50% { opacity: 1 }}

here is a DEMO

.elementToFadeInAndOut {    width:200px;    height: 200px;    background: red;    -webkit-animation: fadeinout 4s linear forwards;    animation: fadeinout 4s linear forwards;}@-webkit-keyframes fadeinout {  0%,100% { opacity: 0; }  50% { opacity: 1; }}@keyframes fadeinout {  0%,100% { opacity: 0; }  50% { opacity: 1; }}
<div class=elementToFadeInAndOut></div>

Reading: Using CSS animations

You can clean the code by doing this:

.elementToFadeInAndOut {    width:200px;    height: 200px;    background: red;    -webkit-animation: fadeinout 4s linear forwards;    animation: fadeinout 4s linear forwards;    opacity: 0;}@-webkit-keyframes fadeinout {  50% { opacity: 1; }}@keyframes fadeinout {  50% { opacity: 1; }}
<div class=elementToFadeInAndOut></div>


If you need a single fadeIn/Out without an explicit user action (like a mouseover/mouseout) you may use a CSS3 animation: http://codepen.io/anon/pen/bdEpwW

.elementToFadeInAndOut {    animation: fadeinout 4s linear 1 forwards;}@keyframes fadeinout {  0% { opacity: 0; }  50% { opacity: 1; }  100% { opacity: 0; }}

By setting animation-fill-mode: forwards the animation will retain its last keyframe

By setting animation-iteration-count: 1 the animation will run just once (change this value if you need to repeat the effect more than once)


I found this link to be useful: css-tricks fade-in fade-out css.

Here's a summary of the csstricks post:

CSS classes:

.m-fadeOut {  visibility: hidden;  opacity: 0;  transition: visibility 0s linear 300ms, opacity 300ms;}.m-fadeIn {  visibility: visible;  opacity: 1;  transition: visibility 0s linear 0s, opacity 300ms;}

In React:

toggle(){    if(true condition){        this.setState({toggleClass: "m-fadeIn"});    }else{        this.setState({toggleClass: "m-fadeOut"});    }}render(){    return (<div className={this.state.toggleClass}>Element to be toggled</div>)}

Belum ada Komentar untuk "CSS How To Make An Element Fade In And Then Fade Out?"

Posting Komentar

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel