Lemondoge
Lemondoge

Reputation: 989

How to animate an element from top-left to bottom-right inside its container?

I made a little "ultimate DVD screensaver" thing for fun, where a disc is animated to precisely hit corners, but for some reason the disc overshoots the bottom-right corner:

#box {
  border: solid;
  height: 85vmin;
  width: 85vmin;
  margin: auto;
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
}

#screensaver {
  position: relative;
  animation: DVD 5s linear infinite alternate;
  left: 0px;
  top: 0px;
}

@keyframes DVD {
  to {
    left: 100%;
    top: 100%;
  }
}
<div id="box"><span id="screensaver">O</span></div>

I've already tried using margin and padding instead of position, and animating from left: 0; top: 0 to right: 0; bottom: 0. Does anyone know why this happens, and if there's a way to solve it without having to fiddle with anything (e.g. if I change the height or width, I don't want to have to change anything else to make it work)?

Upvotes: 3

Views: 3141

Answers (3)

xIsra
xIsra

Reputation: 915

Left and top position are targeted at the top left corner of the animated object.

Use calc() css3 method to subtract the height and width of the object

@keyframes DVD {
  to {
    left: calc(100% - 10px);
    top: calc(100% - 10px);
  }
}

Upvotes: 0

Shawn -
Shawn -

Reputation: 109

hope this code help you

change value.

form

@keyframes DVD {
  to {
    left: 100%;
    top: 100%;
  }
}

to

@keyframes DVD {
      to {
        left: 95%;
        top: 92%;
      }
    }

#box {
  border: solid;
  height: 85vmin;
  width: 85vmin;
  margin: auto;
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
}

#screensaver {
  position: relative;
  animation: DVD 5s linear infinite alternate;
  left: 0px;
  top: 0px;
}

@keyframes DVD {
  to {
    left: 95%;
    top: 92%;
  }
}
<div id="box"><span id="screensaver">O</span></div>

Upvotes: 0

Temani Afif
Temani Afif

Reputation: 272965

use a translation to rectify:

#box {
  border: solid;
  height: 85vmin;
  width: 85vmin;
  margin: auto;
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
}

#screensaver {
  position: relative;
  display:inline-block; /* don't forget this to be able to apply a transform */
  animation: DVD 5s linear infinite alternate;
  left: 0px;
  top: 0px;
}

@keyframes DVD {
  to {
    left: 100%;
    top: 100%;
    transform:translate(-100%,-100%);
  }
}
<div id="box"><span id="screensaver">O</span></div>

Upvotes: 3

Related Questions