- How CSS Works
- A Basic Stylesheet
- A CSS Style Primer
- Using Style Classes
- Using Style IDs
- Internal Stylesheets and Inline Styles
- Summary
- Q&A
- Workshop
Internal Stylesheets and Inline Styles
In some situations, you want to specify styles that will be used in only one web page. You can enclose a stylesheet between <style> and </style> tags and include it directly in an HTML document. Stylesheets used in this manner must appear in the <head> of an HTML document. No <link /> tag is needed, and you cannot refer to that stylesheet from any other page (unless you copy it into the beginning of that document, too). This kind of stylesheet is known as an internal stylesheet, as you learned earlier in the hour.
Listing 3.3 shows an example of how you might specify an internal stylesheet.
LISTING 3.3 A Web Page with an Internal Stylesheet
<!DOCTYPE html><html
lang
="en"
>
<head>
<title>
Some Page</title>
<style
type
="text/css"
>footer {
font-size: 9pt;
line-height: 12pt;
text-align: center;
}
</style>
</head>
<body>
...<footer>
Copyright 2013 Acme Products, Inc.</footer>
</body>
</html>
In the listing code, the footer style class is specified in an internal stylesheet that appears in the head of the page. The style class is now available for use within the body of this page. In fact, it is used in the body of the page to style the copyright notice.
Internal stylesheets are handy if you want to create a style rule that is used multiple times within a single page. However, in some instances, you might need to apply a unique style to one particular element. This calls for an inline style rule, which allows you to specify a style for only a small part of a page, such as an individual element. For example, you can create and apply a style rule within a <p>, <div>, or <span> tag via the style attribute. This type of style is known as an inline style because it is specified right there in the middle of the HTML code.
Here’s how a sample style attribute might look:
<p
style
="color:green
">
This text is green, but<span
style
="color:red"
>
this text is red.</span>
Back to green again, but...</p>
<p>
...now the green is over, and we're back to the default color for this page.</p>
This code makes use of the <span> tag to show how to apply the color style property in an inline style rule. In fact, both the <p> tag and the <span> tag in this example use the color property as an inline style. What’s important to understand is that the color:red style property overrides the color:green style property for the text between the <span> and </span> tags. Then in the second paragraph, neither of the color styles applies because it is a completely new paragraph that adheres to the default color of the entire page.