Use background-size on background applied via inline CSS

796 Views Asked by At

I'm applying a background with an inline style because it needs updated with PHP:

<div style="background:url(img.jpg)">
    test
</div>

At a certain breakpoint, I need to apply background-size:contain;

@media screen and (max-width: 600px) {
    div {
        background-size:contain;
    }
}

Edit- It seems that CSS from a stylesheet does not apply when combined with inline CSS in this case. Is there a solution for that?

Here's a simple jsFiddle -> http://jsfiddle.net/z5r1hwmq/

3

There are 3 best solutions below

1
On BEST ANSWER

You can try by adding !important, for example

background-size:contain!important;

However, this is not the best option. It changes the size, but it would be better if you had real structure that you're using so you can get needed element via parent elements and would be able to do this without adding "!important".

0
On

You can dinamically add/change a class with php to a element instead of inline style.

Also You need to add priority to the css class like this background-size:contain !important; otherwise the inline styles have priority.

Hope this helps.

2
On

Just use background-image instead of background so you don't override all the background options and won't need the !important ;)

<div style="background-image:url(img.jpg)">
   test
</div>