Rex_C February 2016

Background images not loading when used in media queries

I have a pretty standard MVC template I'm using for a project. On a view in my project, I am trying to display a different background image depending on my screen width. The problem is that if I wrap the CSS in media queries then push the content up to a development server, my background images don't load. I don't have this problem in localhost though. I'm using Bootstrap in my project, but this particular CSS is written in a separate file. Also, this project sits in another project on my server.

/Root Project
 --My Project

CSS:

html {
background: url(/Images/img1.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
-ms-background-size: cover;
background-size: cover;
}

@media (max-width: 768px) {
html {
    background: url(/Images/img2.jpg) no-repeat center center fixed;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    -ms-background-size: cover;
    background-size: cover;
    }
    .center-margin {
    margin-top: 30%;
    }
    .header-text {
    color: black;
    }
}

The header in my HTML has the following metadata tags:

<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
</head>

After I took the media query off the first html block in my CSS, it started displaying again. The second block wrapped in the media query won't display. The other CSS inside the media query displays, so its just the background image that is giving me issues.

Answers


Tim Troiano February 2016

Your code is working. You should make sure that your image resources are uploaded to your server in the correct directory. Also, typically for loading URLs you're going to want to put them in quotes.

html {
  background: url("http://www.joomlaworks.net/images/demos/galleries/abstract/7.jpg") no-repeat center center fixed;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  -ms-background-size: cover;
  background-size: cover;
}

@media (max-width: 768px) {
  htm

l {
    background: url("http://www.keenthemes.com/preview/metronic/theme/assets/global/plugins/jcrop/demos/demo_files/image1.jpg") no-repeat center center fixed;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    -ms-background-size: cover;
    background-size: cover;
  }
  .center-margin {
    margin-top: 30%;
  }
  .header-text {
    color: black;
  }
}

Here is a Codepen of this working with images hosted online.

Post Status

Asked in February 2016
Viewed 3,374 times
Voted 7
Answered 1 times

Search




Leave an answer