how to set different image background for the same section on mobiles

Viewed 43

I am working on one page website and I set one background image for all sections using a div like the following :

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

in css my code is the following :

.sec{
      background-repeat: no-repeat;
      background-size:cover;
     }

all is working fine but the mobile doesn't look pleasant to me so i tried to add different background image url to my css with no luck like the following :

@media only screen and (max-width: 600px) {
.sec{
    background-repeat: no-repeat;
     background-size:cover;
     background-image: url(/img/1255.jpg);
    }
}

I just want to know which part I am missing and why I cant have 2 different images for different resolution

3 Answers

You are having this problem because inline css overrides internal/external css, see here. Change your code to

<div class="sec">
</div>

and

.sec{
      background-repeat: no-repeat;
      background-size:cover;
      background-image: url(./img/12.jpg)
     }
@media only screen and (max-width: 600px) {
.sec{
    background-repeat: no-repeat;
     background-size:cover;
     background-image: url(/img/1255.jpg);
    }
}

The style property in thr div gains precedence over the CSS one so probably that's the reason why the second image won't come. It'd be better to do it all in CSS. Check the example below.

.sec {
  // You can ignore the height and width
  width: 100vw;
  height: 100vh;
  background-repeat: no-repeat;
  background-size: cover;
  background-image: url('https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885__340.jpg');
}

@media only screen and (max-width: 400px) {
  .sec {
    background-image: url('https://fsb.zobj.net/crop.php?r=TQ17OTvRvqIRq6m-kcLMlU-g68IHkNtXYQ5B3j9twk_CkS6zM7rH_C-OzOS4iVM6pDE9P2fHuo3Swz1_qVGWT7gRAIxzDby0x7rrCtfroFsHSC7aau-HbAFN7i6SGowXNJmowCJGeoUz5S-Uj16rIKacUVpvxTXLR4YhxW2NK_BXHJErHMF1oh7lD4k');
  }
}
<div class="sec"></div>

you can do same way just add background-image: url(/img/1255.jpg)!important in the mobile device.

Related