O'Reilly logo

Learning PHP, MySQL, JavaScript, and CSS, 2nd Edition by Robin Nixon

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Importing a Style Sheet

When you wish to style a whole site, rather than a single page, a better way to manage styles is to move them out of your web pages into separate files, called style sheets, and then import the ones you need. This minimizes the amount of code that is duplicated across your pages, aiding maintainability, and allows you to apply different style sheets for different layouts (such as web and print) without changing the HTML. Such separation of content from layout is a fundamental principle of design.

There are a couple of different ways this can be achieved, the first of which is by using the CSS @import directive, like this:

<style>
    @import url('styles.css');
</style>

This statement tells the browser to fetch a style sheet with the name styles.css. The @import command is quite flexible in that you can create style sheets that themselves pull in other style sheets, and so on. Just make sure that there are no <style> or </style> tags in any of your external style sheets, or they will not work.

Importing a Style Sheet from Within HTML

You can also include a style sheet with the HTML <link> tag, like this:

<link rel='stylesheet' type='text/css' href='styles.css' />

This has the exact same effect as the @import directive, except that <link> is an HTML-only tag and is not a valid style directive, so it cannot be used from within one style sheet to pull in another. It also cannot be placed within a pair of <style>...</style> tags.

Just as you can use multiple @import directives ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required