Rob Kwasowski
Rob Kwasowski

Reputation: 2780

CSS: overlaying images in animation

I want two images to come down from above the top of the page and have the second one partially cover the first one.
When the position is set to absolute the covering works, but they do not come from above the page, they appear near the bottom. When the position is set to relative they do come from above the top, but the covering doesn't work.
Is there a way to do what I'm looking for?

.float {
  position: relative;
  opacity: 0;}
@keyframes floatBubble {
  0% {bottom:100px; opacity: 1;}
  100% {bottom: 0px; opacity: 1;}}
  
#f1 {animation: floatBubble 0.5s linear 0.5s forwards;left:0px}
#f2 {animation: floatBubble 0.5s linear 0.8s forwards;left:48px}
<img src="https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcQ6uw_6wpFz6VWeLQhsUtQlFw7m2H4YCUSK58JQ7aoGO9Vs8ZS1" height="100px" width="100px" class="float" id="f1">

<img src="https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcQ6uw_6wpFz6VWeLQhsUtQlFw7m2H4YCUSK58JQ7aoGO9Vs8ZS1" height="100px" width="100px" class="float" id="f2">

Upvotes: 2

Views: 56

Answers (1)

Temani Afif
Temani Afif

Reputation: 272965

So think differently and use top instead of bottom and you can use absolute position to achieve the needed effect:

.float {
  position: absolute;
  opacity: 0;
  top:-100px;
}

@keyframes floatBubble {
  0% {
    top: -100px;
    opacity: 1;
  }
  100% {
    top: 0px;
    opacity: 1;
  }
}

#f1 {
  animation: floatBubble 0.5s linear 0.5s forwards;
  left: 0px
}

#f2 {
  animation: floatBubble 0.5s linear 0.8s forwards;
  left: 48px
}
<img src="https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcQ6uw_6wpFz6VWeLQhsUtQlFw7m2H4YCUSK58JQ7aoGO9Vs8ZS1" height="100px" width="100px" class="float" id="f1">

<img src="https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcQ6uw_6wpFz6VWeLQhsUtQlFw7m2H4YCUSK58JQ7aoGO9Vs8ZS1" height="100px" width="100px" class="float" id="f2">

For the explanation

When using relative position, left/bottom are calculated relative to the initial position of the image that's why they don't overlap as you simply push the second one more to the left, so you make them far.

When using absolute position, theses value are calculated relative to the nearest positioned ancestor. In your case there is no such element so they are relative to the document and that's why you get them placed at the bottom.

https://www.w3schools.com/css/css_positioning.asp

https://developer.mozilla.org/en-US/docs/Web/CSS/position

Upvotes: 4

Related Questions