Slide right effect with pure CSS

20,468

You could define @keyframes and use percentage values for the transform property if the width is unknown.

div {
  width: 100px;
  height: 100px;
  background: plum;
  transform: translateX(100%);
  position: fixed;
  -webkit-animation: anim 3.5s 1;
  animation: anim 3.5s 1;
}
@-webkit-keyframes anim {
  0% {
    transform: translateX(100%);
  }
  14.28% {
    transform: translateX(0);
  }
  85.71% {
    transform: translateX(0);
  }
  100% {
    transform: translateX(100%);
  }
}
@keyframes anim {
  0% {
    transform: translateX(100%);
  }
  14.28% {
    transform: translateX(0);
  }
  85.71% {
    transform: translateX(0);
  }
  100% {
    transform: translateX(100%);
  }
}
<div></div>

Share:
20,468
Robo Robok
Author by

Robo Robok

Updated on July 09, 2022

Comments

  • Robo Robok
    Robo Robok almost 2 years

    I need to make certain element (with position: fixed) slide from the right side of the screen, stay there for a while and hide from right again. I don't know the width, which makes it harder to achieve. I did it with jQuery before, but I'd like to use pure CSS. Is that possible? I don't mind using third party solution.

    Here's my jQuery code:

    $("element")
        .css("right", -$("element").outerWidth() + "px")
        .animate({right: 0}, 800)
        .delay(3000)
        .animate({right: -$("element").outerWidth() + "px"}, 800);
    
    • Waxi
      Waxi over 9 years
      This doesn't mean anything without any HTML. And you don't know the width of what? Animations can be done with CSS, but how do you plan on triggering it?
  • Waxi
    Waxi over 9 years
    Pretty cool effect, but using CSS for animation always feels clunky.
  • Ruan Mendes
    Ruan Mendes over 9 years
    @slime You better get using to that clunkiness, it's here to stay
  • Waxi
    Waxi over 9 years
    @JuanMendes For some people sure, but using % to figure out time intervals is annoyingly stupid and needs to be reworked and I won't support it until something better is in place.
  • Weafs.py
    Weafs.py over 9 years
    @slime - The tiltle says pure CSS, Period! Btw, its not some hardcore math. Simply 100% / 7 = 14.28% and 100% - 14.28% = 85.71%.
  • Robo Robok
    Robo Robok over 9 years
    It works pretty nice, but there's one problem. Right -100% is actually window's width distance from the edge, not element's edge. That produces a delay before element gets into place. Can it be moved by element's width instead?
  • Weafs.py
    Weafs.py over 9 years
    @RoboRobok - Yes, you could use the transform property. I've updated the answer.
  • Robo Robok
    Robo Robok over 9 years
    I needed to add right and top properties, but other than that it works perfectly! :)