The previous article in this series highlighted the design goals and assumptions underlying Cascading Style Sheets (CSS), a standard language for applying style characteristics to the elements of Web documents. This article continues our look at CSS with a closer examination of its core elements and functionality.
As the previous article noted, the purpose of CSS is to enable Web developers to apply style characteristics such as text colors and size, font family, spacing, and positioning to the elements of Web documents. However, CSS also enables developers to structure and encapsulate these display rules in ways that help to improve maintainability and code reuse across the application.
The major structural elements of CSS include style sheets, attribute-value pairs, and binding. An understanding of these is important to using CSS effectively.
CSS provides three methods for associating styles with HTML elements. The first of these, inline styles, is illustrated in Listing 1.
Listing 1: Inline Styles
<html> <head> <title>Sample HTML Document </title> </head> <body> <p Style="font-family:Helvetica; font-size:24pt; color:red">Inline Style</p> <p>No Style</p> </body> </html>
The style rules are specified as the value associated with the Style attribute of the <p> tag, in the previous example. Inline styles apply only to the document element in which they are embedded.
Although this method of embedding styles directly within the HTML code is simple and is often used, the style sheet is a better approach. As the previous article mentioned, a style sheet is the encapsulation of style rules in a centralized location. The Web browser reads these styles and applies the specified formatting rules before displaying the content. Style sheets can exist either as separate document elements in the head section of the HTML document or as separate, external files.
Style sheets defined in the head section of the HTML document apply to the entire document in which they are located. Style sheets that exist as external files can be linked to Web documents using the href attribute of the <link> tag. The Web server software reads the linked style sheet when the page is requested, and the contents of the style sheet are inserted into the HTML stream before being sent to the browser. This way, a single style sheet can be shared among a number of pages.
The various ways of structuring and using style sheets, along with their pros and cons, will be discussed further in the next article of this series.