1

Remove background image css or jquery (preferably css).

I've a situation where I cannot set background image using css.

I read all similar question here in stackoverflow but I couldn't find the solution.

html

<div class="foo" style="background-image:url(http://example.com/gallery/albums/foo.jpg);">
 </div>

css

.foo{
    width 400px;
    height:300px;
}
@media screen and (max-width: 200px) {
    .foo{
        background-image: none;
    }  
}

JSFIDDLE Here

Puni
  • 1,214
  • 2
  • 18
  • 34

2 Answers2

0

The problem is that you're using an inline style for the background-image and a css class for the media query style and inline styles are more specific.

Try this:

https://jsfiddle.net/6t7ksdaL/3/

.foo{
    width 400px;
    height:300px;
    background-image:url(http://strabo.com/gallery/albums/wallpaper/foo_wallpaper.sized.jpg);
}
@media screen and (max-width: 200px) {
    .foo{
        background-image: none;
    }  
}

The background image is now defined in the css class so it's specificity is the same as the media query css. The over-ride kicks in when the screen resizes.

Please note that it is a very good idea to pay attention to css specificity as your code will be much more maintainable in the future.

Toni Leigh
  • 4,830
  • 3
  • 22
  • 36
  • Yes exactly the background image is set inline and that's the problem – Puni Jul 20 '15 at 19:05
  • Alright I'll keep that in mind but here I've a situation where I cannot set background image using css. – Puni Jul 20 '15 at 19:15
  • @Puni how is the background image set and do you have control over the code that sets it? – Toni Leigh Jul 20 '15 at 19:31
  • @Puni - waiting to find out response in order to edit my answer to help :-) – Toni Leigh Jul 22 '15 at 09:58
  • @Puni basically, my advice would be only to use `!important`in that context, if you have control over the source of the inline styles, but, if you do, switch them to [`.addClass()`](https://api.jquery.com/addclass/) calls rather than [`.css()`](https://api.jquery.com/css/) calls so you can keep the styles in the css and avoid this specificity issue :-) – Toni Leigh Jul 26 '15 at 18:16
-1

This will work as soon as you add the background to the external css definition and remove it from the inline styles.

The inline css always has precedence before the external css - that way, your @media-query is overwritten by the inline-css.

.foo {
  width 400px;
  height: 300px;
  background-image: url(http://strabo.com/gallery/albums/wallpaper/foo_wallpaper.sized.jpg);
}
@media screen and (max-width: 200px) {
  .foo {
    background-image: none;
  }
}
<div class="foo">
</div>
dhh
  • 4,289
  • 8
  • 42
  • 59