There is a way of including a stylesheet within another while having the two as totally separate files. This is called importing. Imports can be placed in any order that gives you the precedence of rules that you need, but they must be placed before any rules in the stylesheet they are being imported to.
Importing a stylesheet is quite simple. You start with the word @import
and follow it up with the URI. If you wish to specify media, the media name follows the URI. Then you follow everything up with a semicolon.
The rule
is used in the stylesheet of this very book, allowing for the numbering of my chapters.@import url('./chapter_numbers.css');
Ultimately, a stylesheet, whether imported or associated with the document through a link
element, will affect how a page looks. However, there are subtle differences of which you should be aware.
style1.css
into style2.css
(@import
)style1.css
is treated as part of style2.css
, so while you can link to style1.css
but not style2.css
, any page that links to style2.css
is automatically linked to both.style1.css
and style2.css
(link
)style1.css
and style2.css
are treated as separate files, which means you can link to style1.css
and not style2.css
, style2.css
and not style1.css
, or to both (which would require two link
elements).Which you use is up to you. If style1.css
is integral to style2.css
, then I would suggest importing it— especially if style1.css
is integral to other stylesheets as well! For example, chapter_numbers.css
is used with no less than six other stylesheets. If style1.css
is simply a tweak or overrides style2.css
for specific pages, then I'd link to both of them.
There's a trick you don't see often anymore since most browsers today don't need it. In the early days of CSS 2, a lot of older browsers didn't support it properly, and would become confused by the newer rules. Considering these newer rules pertained to layout and the CSS box model, things could get messy indeed.
One thing they didn't support at all was stylesheet importing; imported stylesheets were simply ignored.
This was used to webdesigners' advantage: a basic stylesheet was supplied to all browsers, and more complex ones were imported, usually through the stylesheet created by the style
element.