junaid junaid - 20 days ago 8
CSS Question

i want my background image to be fixed on desktop and scroll on mobile i am not able to change background image from fixed to scroll

I want my background image to be fixed on desktop and scrolling on mobile but background attachment in media query is not working.

<style type="text/css">
@media only screen and (max-width: 991px ){
.post-image{
height: 40vh;
background-attachment:scroll;
}
}

.post-image{
height: 50vh;
background-attachment: fixed;


}



</style>


i have added background image by inline css







header




some text


Answer

You need to change the order of your CSS rules. Media queries do not add any level of specificity to the enclosed CSS rules, so what happens is you overwrite your own mediaqueried rule by a non-media-queried, general rule because it comes after the mediaqueried rule in your CSS source order. Whenever there are several conflicting rules with the same specificity, the last one wins.

<style type="text/css">
@media only screen and (max-width: 991px ){ // this tells the browser to only apply the following set of rules if the condition is met
  .post-image{
    height: 40vh;
    background-attachment:scroll;
  }
}

.post-image{ // this tells the browser to apply the following rules not considering any conditions other than those specified by the selector
  height: 50vh;
  background-attachment: fixed;
}
</style>

So to get what you want, put your media queries at the end of your source code:

<style type="text/css">
.post-image{ 
  height: 50vh;
  background-attachment: fixed;
}
@media only screen and (max-width: 991px) { 
  .post-image{
    height: 40vh;
    background-attachment:scroll;
  }
}
</style>