Background-position not working with CSS animation and linear gradient
Asked Answered
N

2

7

I'm attempting to use CSS3 (gradients and animations) to make an animation similar to the iphone slide to unlock gradient. However, for some reason, the background-position only works when I use static pixel numbers and not when I use percentages. Ideally, I'd be able to apply this class to any element, and have the animation work, without needing to code for specific widths. Can somebody point me in the right direction?

JSFiddle: https://jsfiddle.net/ekLamtbL/

.slideToUnlock {
  background: linear-gradient(-90deg, black 0%, gray 40%, white 45%, gray 55%, black 60%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  color: transparent;
    -webkit-animation: slidetounlock 5s infinite;
    animation: slidetounlock 5s infinite;
    -webkit-animation-direction: normal;
    animation-direction: normal;
}

@-webkit-keyframes slidetounlock {
  0% {
    background-position: -100% 0;
  }
  100% {
    background-position: 100% 0;
  }
}
Nonbelligerent answered 14/4, 2016 at 2:9 Comment(4)
Consider using viewport width instead of percentage? (100vw)Entoblast
@Entoblast for the background percentage or the gradient?Nonbelligerent
Placed it on the background position: jsfiddle.net/7wLtzvLr Perhaps I misunderstood.Entoblast
That makes it loop quite a bit. Ideally, it would move one full width across, then start over at the beginningNonbelligerent
A
9

Added your code

background-size: 250% 250%;

Example

.slideToUnlock {
  background: linear-gradient(-90deg, black 0%, gray 40%, white 45%, gray 55%, black 60%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  color: transparent;
  -webkit-animation: slidetounlock 5s infinite;
  animation: slidetounlock 5s infinite;
  -webkit-animation-direction: normal;
  animation-direction: normal;
  background-size: 250% 250%;
}

https://jsfiddle.net/ekLamtbL/2/

Auric answered 14/4, 2016 at 3:14 Comment(2)
Can you explain why background-size: 250% 250%; works here?Customary
@Customary Lutymane actually answers it in their answer.Perfume
P
3

Article on MDN explains it well

tldr: To make a use of percentage background-position your background's size should not equal to 100% of the dimension you want to position. N% position means N% of the background is mapped to N% of the element. Since gradient automatically has size of 100%x100% setting background-position seem to have no effect unless you set background-size to some value like 200% for example

Protist answered 30/5, 2022 at 2:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.