How to change background-position property?

Asked

Viewed 89 times

1

I would like to know a javascript that changes the background-position of a particular div.

I’m trying to get the position of the background.

  • Can I put the value of type 30, 20? inside quotation marks?

  • I think not, the properties are like: top, left, center, bottom...I believe that values are not allowed.

1 answer

2


Use backgroundPosition:

document.querySelector('div').style.backgroundPosition = '50% 50%';
div {
  background: url(http://i.stack.imgur.com/c9dbY.jpg) no-repeat;
  height: 200px;
  width: 200px
}
<div></div>

To change the background position from one point to the other, you do not need Javascript. You can create your own rule that changes the position with @keyframes and apply to a property animation:

@keyframes minha-animacao {
  from { background-position: 0 0 }
  to   { background-position: 100% 50% }
}

div {
  animation: minha-animacao 4s linear forwards;
  background: url(http://i.stack.imgur.com/c9dbY.jpg) no-repeat;
  height: 300px;
  width: 300px
}
<div></div>


Property support animation

  • By the way, if you want to change the background.position in real time, how do I do? I mean, it’s 50px, and changing up to 80 px in real time, like it’s 51px, 52 px, 53 px, 54 px... until it’s 80? And may all these changes be noted on the site.

  • Loop with Javascript or use CSS animations.

  • Can you give me an example please, I’m a little new

  • @Gonçalo Feito, with CSS. Then edit your question and explain that you are looking to change the background position between two points. Comments are disposable.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.