CSS External

External styles

The true power of CSS is separating presentation from content. External stylesheets are the tool for doing exactly this. By putting all your CSS rules into a separate .css file (a simple text file) you can re-use them for all your pages without rewriting. All your styles are in a centralized place making it easy to maintain and change the look of your website.

Linking external stylesheets

To include one or more stylesheets into your HTML document you can use the <link ... /> element inside the HTML <head>.

External CSS:

  • <head>
  •   <title>External CSS styles</title>
  •   <link type="text/css" rel="stylesheet" media="all" href="style.css" />
  • </head>
  • type:

    This is the MIME content-type and should always be set to text/css for stylesheets.
  • rel:

    This attribute describes the relationship between the actual document and the one you're linking to. In this case it's always stylesheet.
  • media:

    You might want to provide more than one stylesheet for different presentations of your website. For example a normal one, a high-contrast one for people with reading difficulties, a printer-friendly one for printing and so on. If the client supports this it will use the appropriate stylesheet. If you just have a single stylesheet for everything you can omit this attribute or use all.
  • href:

    This is the link to your stylesheet.

Usage guidelines

1. Use as much as possible

Try to put all your CSS styles into stylesheets and minimize your inline CSS and internal CSS.

2. Use a logical structure

As a CSS beginner you probably won't care much about the order in which you write your CSS rules because your stylesheets will be relatively small. As they get bigger, though, it can help having a logical structure in your stylesheet. For example you could group general selectors such as body, a, p, img, h1, ... at the beginning and then follow with contextual selector rules. Or group CSS styles together which belong to a certain layout part of the page such as the header, sidebar, footer and so on.

3. Naming your stylesheet

It's an unofficial naming convention that the main stylesheet is called style.css. It can't hurt adopting this yourself.

4. Use F5 to display recent changes

When you're making changes to your stylesheets you have to press the F5 key to force the web browser to load the newest version instead of using the cached one.