SporeDev
SporeDev

Reputation: 608

Opacity transition without hover

I have the following class:

.dot{
  width:40px;
  height:40px;
  position:absolute;
  background: url(https://www.sporedev.ro/pleiade/images/Frunza.png);
  background-size: 100% 100%;
  z-index:999;
  margin-top:-60%; 
  pointer-events:none; 
}

I modified the class like this:

.dot{
  width:40px;
  height:40px;
  position:absolute;
  background: url(https://www.sporedev.ro/pleiade/images/Frunza.png);
  background-size: 100% 100%;
  z-index:999;
  margin-top:-60%; 
  pointer-events:none; 
  -webkit-transition: opacity 1s ease-in-out;
  -moz-transition: opacity 1s ease-in-out;
  -ms-transition: opacity 1s ease-in-out;
  -o-transition: opacity 1s ease-in-out;
  transition: opacity 1s ease-in-out;
}

What I tried to do was to apply a transition so that the div is not initially shown when the page is opened but it reaches opacity: 1; after 1s has passed.

I did some research and all I could find on SO and Google was related to hovering. I tried applying "opacity: 0;" to my class but then the transition wouldn't take place, the div would just stay hidden.

Is there any way to accomplish an opacity transition without a hover state using CSS?

Upvotes: 0

Views: 2393

Answers (3)

Steve Knoblock
Steve Knoblock

Reputation: 33

Yes, use JavaScript to trigger the transition. That is the answer to your question. A transition only happens when there is something to transition to. Just sepcifying a transition on an element does not trigger the transition. Change does. When the element first loads there is nothing to transition to.

Upvotes: 0

Robotnicka
Robotnicka

Reputation: 574

You can achieve this using css animations.

The animation is set using the @keyframes rule. To illustrate in the example, I removed the margin top; this is not a necessary change in your code.

.dot {
  width: 40px;
  height: 40px;
  position: absolute;
  background: url(https://www.sporedev.ro/pleiade/images/Frunza.png);
  background-size: 100% 100%;
  z-index: 999;
  // margin-top:-60%; 
  pointer-events: none;
  animation: fadein 1s ease-in;
}

@keyframes fadein {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}
<div class="dot"></div>

Upvotes: 2

APAD1
APAD1

Reputation: 13666

You can accomplish this with CSS3 animation:

.dot{
  width:40px;
  height:40px;
  position:absolute;
  background:url(https://www.sporedev.ro/pleiade/images/Frunza.png);
  background-size:100% 100%;
  z-index:999;
  pointer-events:none;
  animation:fadeIn 1s ease-in;
}

@keyframes fadeIn {
    from { 
      opacity:0;
    }
    to {
      opacity:1;
    }
}
<div class="dot"></div>

Upvotes: 2

Related Questions