TheLettuceMaster
TheLettuceMaster

Reputation: 15734

Targeting Different Screen Widths with Multiple CSS files

Here are links to my CSS files:

        <link  rel="stylesheet" href="css/mobile_css_320.css" media="screen and (min-device-width: 0px) and (max-device-width: 320px)" />
        <link  rel="stylesheet" href="css/mobile_css_480.css" media="screen and (min-device-width: 321px) and (max-device-width: 480px)" />
        <link  rel="stylesheet" href="css/mobile_css_640.css" media="screen and (min-device-width: 481px) and (max-device-width: 640px)" />
        <link  rel="stylesheet" href="css/mobile_css_720.css" media="screen and (min-device-width: 641px) and (max-device-width: 720px)" />
        <link  rel="stylesheet" href="css/styles.css" media="screen, projection" />

Here is my link in styles.css (for Web Browsers on PC's)

#form_wrapper {
      width: 320px;
      margin: 0 auto;
}

In all other CSS files (targeting Mobile Devices), I do this:

#form_wrapper {
      width: 92%;
      margin: 0 auto;
}

However, in all Mobile devices, it goes straight to the last CSS file, styles.css and I get that div 320px on all devices no matter what.

I have only tested on Google's Chrome for Android on mobile devices as well as the stock Android webkit browser (for Android 4.0+). Is my code handling wrong?

Upvotes: 3

Views: 1233

Answers (2)

Sean
Sean

Reputation: 6499

CSS Specificity states that if two rules are the same e.g.

.text { color: blue; }
.text { color: red; }

Then the last one always prevails (in this case anything with a class of text would have red text)

So as your last stylesheet has no media query attached to it, it is always loading, and always overiding any styles you put in the mobile stylesheets before it.

To counteract this you could:

1) Put the desktop stylesheet first

2) Use a min-width media query on the last stylesheet, e.g.

<link  rel="stylesheet" href="css/styles.css" media="media="screen and (min-device-width: 720px)" />

Upvotes: 1

Thomas Jones
Thomas Jones

Reputation: 4962

Its probably loading all of them that are relevant, and since the last one is the most generic (mobile devices will match the media screen), it overwrites all styles defined in the previous stylesheets. CSS is a last-in wins in cases of a tie in specificity.

Try putting your generic stylesheet first, or combining them using media queries directly in the stylesheet itself.

Upvotes: 4

Related Questions