As a site’s CSS grows in size and complexity with more vendor prefixes, transitions and media queries, it becomes harder to track and maintain all the declarations that make up the code. At a certain point, it makes sense to divide a site’s CSS up into structured components, rather than scrolling up and down a single long stylesheet to find and make changes.
Dividing Large Stylesheets For Development
There are a few ways of dividing your CSS. The obvious method is to create declarations for various components and then link them as separate stylesheets. Typically, these components would include a reset stylesheet, a base CSS file that sizes page elements, typography, a set of media queries, and a print stylesheet:
<head>
<title>Page Title</title>
<link rel="stylesheet" href="reset.css">
<link rel="stylesheet" href="base.css">
<link rel="stylesheet" href="typography.css">
<link rel="stylesheet" href="tablet.css" media="screen and (max-width:720px)">
<link rel="stylesheet" href="print.css" media="print">
</head>
The downside of this approach is that it adds quite a bit of code to the <head>
of each page and forces new components to be added to each page separately. Alternatively, you can use @import
rules in the code of a single .css file. The only requirement is that the @import
code must be at the very start of the CSS page. In this case, I will add the following to the top of the base.css code:
@import url(reset.css)
@import url(typography.css)
@import url(tablet.css) screen and (max-width:720px)
@import url(print.css) print
body { color: #ccc; … }
This means that we need to link only the base.css file from each HTML page:
<head>
<title>Page Title</title>
<link rel="stylesheet" href="base.css">
</head>
The other stylesheets will be imported from base.css, much like server-side includes in PHP.
This technique works in all modern browsers, although it should be noted that historically IE 7 and earlier have struggled with the method. Modern CSS pre-processors such as Sass use a similar method to divide stylesheet code into logical structures that can be dealt with separately.
Not For Production
It’s important to understand that this technique is designed to optimize workflow during development of larger sites: it is not intended for production. On a live public site, the ideal solution is the opposite: to deliver as few CSS files as possible. I’ll discuss how to achieve that in the context of migrating development CSS to production code in an upcoming article.
Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.