Spencer Speas
Spencer Speas

Reputation: 11

How to create variables in javascript for background-position?

I am trying to create a variable for my background-position in Javascript/CSS. I am very new to programming, and a developer friend of mine wrote the original code and I am having trouble assigning my background-position to a variable.

<style>
.frame{
  width: 354.1875px;
  var viewWidth = 354.1875px;
  height: 415px;
  background-image: url(https://website.com/image.jpg);
  background-repeat: no-repeat;
  background-position: 0 50%;
}
.frame1 {
  background-position: -1*viewWidth 50%;
}
.frame2 {
  background-position: -2*viewWidth 50%;
} 
.frame3 {
  background-position: -600px 50%;
}

Frames 1 and 2 are where I have tried to use my variable, from what I've googled it should work, can someone please help me here?

Upvotes: 0

Views: 75

Answers (1)

Andy Hoffman
Andy Hoffman

Reputation: 19109

You're maybe thinking of CSS Custom Properties which you could use in the following way.

Custom properties (sometimes referred to as CSS variables or cascading variables) are entities defined by CSS authors that contain specific values to be reused throughout a document.

:root {
  --viewWidth: 354.1875px;
}

.frame{
  width: var(--viewWidth);
  height: 415px;
  background-image: url(https://website.com/image.jpg);
  background-repeat: no-repeat;
  background-position: 0 50%;
}
.frame1 {
  background-position: calc(-1 * var(--viewWidth)) 50%;
}
.frame2 {
  background-position: calc(-2 * var(--viewWidth)) 50%;
} 
.frame3 {
  background-position: -600px 50%;
}

Upvotes: 1

Related Questions