Hi, I have 2 style sheets for my site. One is for small screen and the other is for large screen. Here is the code.

<script type="text/javascript">
if (screen.width >= '900'){
	document.write('<link href="main.css" rel="stylesheet" type="text/css" />');
}else {document.write('<link href="small.css" rel="stylesheet" type="text/css" />');
}
</script>

What I want to do is have the small.css as the default style sheet in case java script is disabled. Currently I have the following above the script tag.

<link href="main.css" rel="stylesheet" type="text/css" />

It works fine if java script is disabled. My question is, is this a correct way to do this?
Thanx.

Dani AI

Generated

Good follow-up. Rather than relying on JavaScript to choose a stylesheet, prefer a CSS-first approach so the small-screen layout is the default and larger rules apply only when the viewport meets your breakpoint. This is more robust, faster and works when JavaScript is disabled.

Simple options:

  • Use two link tags and let the browser apply the large stylesheet only when the viewport matches a media query:
<link rel="stylesheet" href="small.css">
<link rel="stylesheet" href="main.css" media="screen and (min-width: 900px)">
  • Or use a single, mobile-first stylesheet and put the wide-screen overrides in an @media block:
/* base (mobile) rules) */

@media (min-width: 900px) {
  /* wide-screen rules */
}

As suggested, serving the small styles as the default is the right idea — these CSS techniques implement that without JavaScript. Using media queries avoids the fragility of client-side detection (and document.write), gives better caching behavior, and matches how breakpoints are meant to work (they use the CSS viewport width). For details on media queries and the link element, see the MDN documentation: Using media queries and HTML link element.

Recommended Answers

All 2 Replies

yes

Set the small screen css first in the normal way. Then use javascript to over ride this with the wide screen version. No need to mention the small one in the javascript.

Thank you very much, I wasn't sure.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.