Leff Leff - 20 days ago 5
CSS Question

CSS - Image looks differently when adding it dynamically

I have a fiddle, to which I would like to add background image dynamically. I am trying to pass it like so:

<div class="card" style="background:url(http://media.comicbook.com/2016/05/captain-america-civil-war-02082016-182755.png), #0a0a0a;">


But then the image is not the same size as when it is in set in the css file. How can I fix that?

Answer

The problem is that the background is a shorthand property for all background related properties. So setting it on the style overrides all other properties.

The same will happen in CSS if you move that property after all the other ones.

So in CSS you have (and it works)

  background:url(http://media.comicbook.com/2016/05/captain-america-civil-war-02082016-182755.png), #0a0a0a;
  background-position: -60px 42px, 0;
  background-repeat: no-repeat;
  background-size: 70% 88%;

but if you change it to

  background-position: -60px 42px, 0;
  background-repeat: no-repeat;
  background-size: 70% 88%;
  background:url(http://media.comicbook.com/2016/05/captain-america-civil-war-02082016-182755.png), #0a0a0a;

It will not.


The solutin is to just set the style="background-image:url('...');background-color:#0a0a0a" and not the whole background.

Demo at https://jsfiddle.net/zo7rf71q/5/

Comments