Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

Lesson 1: Introducing CSS3 CHAPTER 4 141


but it does not promote reuse across HTML documents. You might use this approach when
you want to have a single, stand-alone HTML document that contains everything needed
to render.

Creating an external style sheet


Instead of creating the same embedded styles in every HTML document, the best approach is
to create an external style sheet file that you can link to all your pages. You can use the <link>
element, as shown in the following example.
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml'>
<head>
<title></title>
<link rel='stylesheet' type='text/css' href='Content/default.css' />
</head>
<body>

</body>
</html>

In this example, the <link> element contains the rel attribute, which specifies the rela-
tionship between the current HTML document and the external file as a style sheet. The
type attribute specifies the MIME type of the external file as a text-based cascading style
sheet. The href attribute specifies the relative location of the external CSS file, which is the
default. css file located in the Content folder. If you want a style rule that locates the <body>
element and sets the background color to white and the font color to gray, you would open
the default.css file and add the following.
body {
background-color: white;
color: gray;
}

A style sheet file can have as many style rules as you need. Using an external style sheet
is considered the best way to implement your styles. You can also link many external style
sheets to an HTML document. For example, your company might create a corporate style
sheet that it expects to be used on all websites that are exposed to the public. In addition to
using the corporate style sheet, you might also create your own style sheet to address specific
needs that your department is working on. In your webpages, you can add a <link> element
for each style sheet.

Using media to specify the target device
The <link> element also has a media attribute that can specify the target device. By using the
media attribute, you can create a CSS file for each device type and link all the CSS files into
your HTML documents. When the HTML document is rendered, the browser determines the
media type and uses the appropriate CSS file. The browser can select only one media type for
Free download pdf