简体   繁体   中英

Media query div background image change weirdness

I have div with a simple background image. I'd need to change the image and how it's being displayed for responsiveness however I see some weird behavior happening when I resize the browser, the cover image either doesn't show at first or shows in pieces, when I resize a second time even if it's just one pixel change it starts showing. Refreshing the browser in any size works just fine. Any idea why this is happening and how to fix it?

.mydiv {
  background: url(../img/background1.jpg) no-repeat;
  background-position: center center;
}

@media (max-width:992px) {
  .mydiv {
    background: url(../img/background2.jpg) no-repeat;
    background-position: center center;
    background-attachment: fixed;
    background-size: cover;
  }
}

Edit: I've noticed that when I inspect element and touch .mydiv the weirdness goes away, so I wonder if there's a way to get Javascript or JQuery to refresh my element or something like that.

I see a couple of things right off the bat:

  1. Add a space between @media and (max-width:992px)
  2. Are you using a mydiv element, or is that supposed to be a class or ID name? If it's a class or id, then you need to refer to it as either .mydiv (class) or #mydiv (ID) in your CSS.

Here's a working jsfiddle.

Rewrite the media query correctly, adding a space and if you wish for more clarity use @media which by itself it's impliciting defining @media all, but you can also use a parameter but then you need to add

I'm using 768px just for testing purposes in this case. Update it with the value you need.

      @media screen and (max-width: 768px) {

      }

DEMO CODE

html,body{
    height:100%;
}
.mydiv {
    width:100%;
    height:100%;
  background: url('http://placehold.it/1000x1000/FFF/000') no-repeat;
  background-size:cover;
  background-position: center center;
}

@media (max-width: 768px) {
  .mydiv {
    background: url(http://placehold.it/1000x1000/) no-repeat;
    background-position: center center;
  }
}

Check this demo:

https://jsfiddle.net/a_incarnati/v575uvyb/5/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM