Home > OS >  Can you chain backgroundImage and backgroundPosition?
Can you chain backgroundImage and backgroundPosition?

Time:03-19

Having trouble figuring out how to use backgroundImage and backgroundPosition with the DOm method. Looking to use the background image and adjust the positioning

 window.onload = function() {
var slime =  "url(https://www.dropbox.com/s/scdx0a0ck16abtv/slime.jpg?raw=1)";
   document.getElementsByTagName('main').style.backgroundImage = "url(https://www.dropbox.com/s/scdx0a0ck16abtv/slime.jpg?raw=1)";
slime.style.backgroundPosition = '25% 75%';
};

CodePudding user response:

I'm breaking this up and adding comments for clarity (what @A Haworth said above is spot on, however).

window.onload = function() {
  // define and store image url with proper formatting
  var slime =  "url('https://www.dropbox.com/s/scdx0a0ck16abtv/slime.jpg?raw=1')";

  // get the main element from the DOM (there are multiple ways of accomplishing this)
  let main = document.querySelector('main');

  // set background image of main element
  main.style.backgroundImage = slime;

  // set position of background image
  main.style.backgroundPosition = '25% 75%';
)};

CodePudding user response:

The "chaining" CSS properties is called shorthand which can apply to some CSS properties. Fortunately backgound property does, here's the list:

background:

  • background-color
  • background-image
  • background-repeat
  • background-attachment
  • background-position

It has to be in that order delimitted with a space, and any value can be omitted (but at least one is needed). So OP would be:

background: url(https://www.dropbox.com/s/scdx0a0ck16abtv/slime.jpg?raw=1) 25% 75%

/* You should add "no-repeat" betwwen -image and -position if the image dimensions 
are smaller than the element's dimension, unless you want a wallpaper effect */

That property: value is referred to as a CSS ruleset. In order to actually apply any CSS ruleset to an element inline with the .style property, is to use .setProperty() method along with it.

node.style.setProperty(property, value);

const main = document.querySelector('main');

const property = 'background';

const value = `url(https://www.dropbox.com/s/scdx0a0ck16abtv/slime.jpg?raw=1) 25% 75%`;

main.style.setProperty(property, value);
html,
body {
  width: 100%;
  height: 100%
}

main {
  min-height: 100%;
}
<main></main>

  • Related