Publishers of technology books, eBooks, and videos for creative people

Home > Articles

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Importing Style Sheets

If you've been wondering throughout the first 15,000 words or so of this chapter just where the word "cascading" in "cascading style sheets" comes in, well, wonder no longer. One of the strengths of CSS is that style sheets can import from other style sheets, enabling us to create, for example, a base style sheet, used across an entire site, and more specialized style sheets, which import from this base style sheet, associated with specific subsections of a site. This way, when the style sheets that are imported into a style sheet change, there's no need to update the style sheets that do the importing—the changes flow, or "cascade" directly into these style sheets, then into the HTML documents they style. The "cascade" is the flow of style from one style sheet into another style sheet via importing.

@import

Any style sheet, whether it's embedded or a stand-alone CSS file, can import another style sheet. We accomplish this with an @import statement, which has the form of the keyword @import, followed by the URL for the imported style sheet (a relative or absolute URL), and optionally a comma-separated list of media types, as we saw a moment ago.

The URL may take either the form of a URL value, like we saw earlier with the background-image and list-style-image properties, or simply the URL alone, but in either case should be quoted with single or double quotation marks. Very importantly, if the URL is relative, it must be relative to the style sheet the @import statement is in, not to the HTML document. (This may sound obvious, but Netscape 4 got this wrong and treated the URL as relative to the HTML document.) Here's how we might import a style sheet for our typography into a main style sheet for a site:

@import url("./style/typography.css")
               

We could import a page layout style sheet for the screen or projection media, and another for printing, like this:

@import url("./style/screenlayout.css") screen, projection
@import url("./style/printlayout.css") print
               

Just as the order of statements in a style sheet is important for the specificity of a statement—statements lower down in the style sheet trump those of the same specificity higher up in the style sheet—the same rule applies in the cascade. Statements lower down in the cascade override those higher up in the cascade.

@import statements must appear in a style sheet above all other statements, and other @ rules like @media. This is so browsers can fetch the imported style sheets before calculating the specificity of all the rules in the style sheet.

  • + Share This
  • 🔖 Save To Your Account