0

I'm building a theme from scratch and I want it to use a different stylesheet for screens below a certain width, for mobile compatibility. I used this method in header.php to call the appropriate stylesheet:

<link rel="stylesheet" href="<?php echo get_stylesheet_directory_uri(); ?>/small.css" type="text/css" media="(max-width: 900px)" />
<link rel="stylesheet" href="<?php echo get_stylesheet_directory_uri(); ?>/style.css" type="text/css" media="(min-width: 900px)" />

WordPress successfully uses the style.css file, but when the browser window scales down enough to call the "small" stylesheet, everything goes haywire: elements are misplaced, things disappear, etc.

I know the problem isn't with the stylesheets themselves, because they work fine when applied to a static HTML capture of the WordPress theme. As far as I can tell, WordPress is trying to call both spreadsheets at once and they are conflicting with each other.

I'm guessing this is not the intended way to implement an alternative stylesheet...?

  • "...because they work fine when applied to a static HTML capture of the WordPress theme" Bit of an X/Y problem here - your conclusion might seem sound but it does not categorically mean that WordPress itself is the issue. WordPress cannot "load" stylesheets, this is handled by the client (browser). Are you sure that the resulting markup from a WordPress request is the same as your static HTML capture? That there's not a plugin getting in the away? Or is there extra/missing JavaScript/CSS in one and not the other? – TheDeadMedic Feb 29 '16 at 17:54
  • And when you're testing the static HTML, are you doing so via file:// in your browser, or over a network? Most browsers will put local files in "safe mode" which prevents certain scripts & network requests from running, which will ultimately render a different environment to the one generated by WordPress – TheDeadMedic Feb 29 '16 at 17:55
  • yes, file://... I guess I should try running it remotely and see what happens. – John Allie Feb 29 '16 at 18:06
0

After further investigations of my own, I determined that the problem was that for whatever reason, both stylesheets were being called at once, rather than independently as they were meant to, and the conflicting instructions caused rendering errors. Rather than referencing the stylesheets in the HTML as above, I rewrote the CSS to incorporate the mobile-size rules within the same file:

@media only screen and (max-device-width: 700px) {
    <rules for smaller screens go here>
}

To write the rules this way requires them to cooperate with the existing rules, but has greater compatibility, and from what I've seen is more in line with current best practices. (Please feel free to speak up if you've heard otherwise.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.