Unit 2 – Cascading Style Sheets Introduction Before you begin the study of Cascading Style Sheets(CSS), you should already be familiar with basic HTML. You need to understand how HTML tags work, know HTML syntax and rules, be able to use HTML to format tables, frames and forms. If you feel you need to brush up on these basics there are several good online tutorials. Try one of the following: www.webmonkey.com www.w3schools.com This unit is intended to enhance your interface programming skills by taking a long look at Cascading Style Sheets and how they can be used in Web interface programming. Lessons 1. 2. 3. 4. Cascading Style Sheets, an Overview Cascading Style Sheets, a Primer Cascading Style Sheets, the Most Useful Features Advanced Cascading Style Sheet Concepts Terms Cascading Style Sheets (CSS) – Cascading style sheets are a specification, developed by W3C, that allow the visual appearance of a Web page or site to be defined in a separate style sheet file. Declaration -- The portion of a CSS rule that sets a Property and Value for a specific HTML tag, which governs the appearance of text delimited by that tag. Dynamic Hypertext Markup Language (DHTML) -- DHTML is the art of making HTML pages dynamic by using scripting to manipulate the style, layout and contents of the document Hypertext -- A connection to another Web page, or location within the current page. When a user clicks the text that contains the hyperlink, the browser displays the Web page targeted by the link. Hypertext links are created with the HTML language. Hypertext Markup Language (HTML) -- HTML is a text-based formatting language used to generically format text for Web pages. It is a simplified derivative of SGML, that tags different parts of a document in terms of their function rather than appearance. A Web browser reads an HTML document and displays it as indicated by the HTML formatting tags and the browser’s default settings. Inheritance – the process by which rights assigned to containers higher in the tree flow down to objects below the container. Kludge -- Kludge (pronounced “klooj”) is an ugly solution to a technical problem, often using techniques or hardware to do jobs they were not designed for. Kludge is a last-ditch approach that gets a job done, but it is not something to be proud of. See hack Pixel -- Computers display graphic images as a series of points on the screen. Each individual point is called a pixel Rule -- A CSS rule identifies an HTML tag, and contains a Declaration which will govern the appearance of any text that is delimited by the tag. Typography -- The arrangement and appearance of displayed content via a communication media. Value -- The Value is the part of a CSS Declaration, which determines a specific attribute that will be assigned to a particular HTML tag, which is identified by the Selector portion of the CSS Rule Declaration. World Wide Web Consortium (W3C) – The W3C is an independent industry organization that works to develop technically sound open standards for the World Wide Web. The W3C is the chief standards organization for HTTP and HTML, and it cooperates with the various Internet organizations. Lesson 1 – Cascading Style Sheets, an Overview HyperText Markup Language (HTML) was never intended to be used as an exacting means for placement of web graphics, nor was it designed to enable stylization of text displayed on a web page. These needs became apparent as the World Wide Web became a significant media for commercial advertising and e-business applications. Objectives At the end of this lesson you should be able to: 1. Understand what Cascading Style Sheets (CSS) is. 2. Understand the pros and cons of CSS. Key Point Cascading Style Sheets (CSS) provides a means to control how Web pages present content. Who created CSS? To address a growing need for a means to precisely control text styling, layout and the positioning of graphics on a web page, the W3C (World Wide Web Consortium) developed and released the CSS Level 1 specification (a W3C“Recommendation”) in December 1996. Cascading Style Sheet Level 1 specification describes the CSS language that provides a simple mechanism to consistently format text and position web graphics on a web page. In May of 1988, Cascading Style Sheet Level 2 specification was released by the W3C. CSS2 picked-up where CSS1 left off, added support for media-specific style sheets such as printers and aural devices, down-loadable fonts, element positioning and tables.. Cascading Style Sheet Level 3 specification is currently under development by the W3C.[W3C] What are Cascading Style Sheets? Cascading style sheets are a set of specifications developed by the W3C, that allow the visual appearance of a Web page or site to be determined by rule sets that can be contained in a separate style sheet file.[CSSDef01] What are the benefits of using CSS? Consistent web page layout and formatting of text Each web page on a web site that makes use of linked Cascading Style Sheet technology will have a consistent look and feel. This is a significant benefit when the content of a web site consists of several thousand web pages; as the layout of all web pages will be consistent according to the specifications contained in the stylesheet(s) for that web site. Saves time and effort when creating HTML documents Font attributes no longer need be declared for every HTML code block. Styles are assigned based on characteristics assigned to HTML tags via a CSS rule sets. Saves time and effort when changing the appearance of a web site Making changes to a web sites' linked CSS file can change the appearance of text delimited by HTML tags, wherever a tag is referenced, throughout an entire web site. Changing rule sets in a linked external CSS file can provide a site with an entire new look and feel, without needing to modify any HTML pages. Reduction in the time required to download and interpret a web page CSS removes the need to specify attributes for each an every HTML tag, which significantly reduces the size of an HTML document, as well as the time needed by the browser to interpret and render the web page. Precise positioning of text and graphics CSS provides a variety of layout controls to enable web developers more precise control over text and graphic positioning in an HTML document. Dynamic HTML features lend support to HTML document enhancements Cursor rollover effects - changing the background color of selected text when the users' cursor is positioned over the text - can be easily achieved using CSS. A popular effect is to underline hyperlinked text only when a user positions their cursor over the text. Web site appearance can be altered to suit a users personal preferences Web developers can use CSS to provide users with the capability to customize the appearance of a web site, by increasing the font size of text, changing the default background color of web pages, etc. Providing a means for users to customize the presentation of HTML documents is one approach to help ensure that a web site is viewable on a variety of system platforms. What challenges are associated with CSS? Developers must still learn the aspects of good web site design and layout A wide variety of Cascading Style Sheets have been designed and can be freely downloaded and used by HTML authors and web developers. While this can be a real time-saver as compared to creating a CSS specification from scratch, developers still need to have knowledge of what qualities and characteristics support effective HTML document layout and presentation. This knowledge is gained through education and trial-and-error experimentation. With this knowledge, web developers are free to choose from a library of Cascading Style Sheet specifications, to use as a starting point toward meeting the needs and requirements of a given HTML-based project or application. Users can still affect the appearance of your web page. Web Browser user preference settings affect page appearance To provide users with maximum flexibility when viewing web content, most popular web browsers provide a Preference setting that enables the web browser to override a web page author's page layout settings. While this capability is useful when the author's chosen page presentation is not optimum for a given user, a browser that is set in error to override an author's style sheet can result in illegible or even unreadable content. CSS design guidelines for authors are in place to ensure that content can be viewed over a wide range of web browser Preference settings. It is still incumbent on users to understand the capabilities of their web browser software, as well as the effect that different Preference settings will have on their viewing experience. Installed fonts determine page appearance The Cascading Style Sheet specification provides for graceful font degradation when a specified font is not available on a users' viewing platform. When working on web development projects that require specific fonts, developers need to ensure that all required fonts are installed and available on their system. Web Browser Issues According to a recent survey, most people surfing the Web use Microsoft's Internet Explorer web browser, which provides good support for Cascading Style Sheets level 1 and 2. Other popular web browser choices such as Netscape and the Open Source Mozilla web browser, also offer good CSS support. Other web browser options, such as the Opera web browser, are improving with respect to CSS support. When developing Cascading Style Sheets for a project, it makes sense to know in advance what the browser and viewing platform the user audience will be using. A CSS specification developed for Apple Mac users who choose Netscape as their browser-of-choice, may vary greatly from a CSS specification for Microsoft Windows-based PC's equipped with Internet Explorer. A little investigation of browser choices and viewing platforms can save considerable work later along the lines of CSS redevelopment. One final issue concerning web browsers and CSS performance - ensure users are using the most recent stable release of web browser software available. While many users are aware that keeping current with web browser updates helps to ensure the security of their system, as well as ensure optimal viewing of a web site, some users remain lax about keeping their web browser software current. Most annoying to web developers is to receive a user complaint of a web page or site not displaying properly, only to learn later that the user using a much outdated and broken version Internet Explorer. Whether you choose to include code in your web pages to autosense browser types and versions, or handle it via a clause in a user agreement, ensure that users understand that they bear the responsibility of maintaining their browser software, as well as understanding the capabilities and settings of their web browser of choice. Lesson 2 – Cascading Style Sheets, a Primer CSS were conceived to fill a lack in the basic capabilities of HTML. By using CSS, an extension to HTML, Web developers can separate the content of a Web page from the instructions that define its appearance. HTML can then define the basic logical structure of a document's information, while style sheets control the presentation of the information over a multitude of browsers and platforms. Objectives At the end of this lesson you should be able to: 1. Discuss the difference between content and appearance, and why they should be separated 2. List some of the major improvements that CSS offers over HTML 3. Explain why CSS are not yet widely used 4. Explain why HTML is a poor tool for controlling page appearance Key Point The key to CSS is the principle of separating a document's content from its appearance What's Wrong With HTML? Actually, there is nothing wrong with HTML. However, there is a lot wrong with the way we are currently using it. To understand this, remember that the Web began as a medium to share text documents. Nobody anticipated the Web would become an advertising channel, shopping mall, or 24-hour gaming arcade. HTML was designed to display documents on a very wide range of simple text monitors. Most systems supported plain American Standard Code for Information Interchange (ASCII) text, but its lack of formatting makes it hard to read and just plain dull. Thus the Web's architects created HTML to describe the internal structure of a document, such as its major headings and subheads ( <H1> to <H6> ), lists ( <OL> , <UL> ), quotations ( <BLOCKQUOTE> ), and other markup appropriate for academic documents. Using this structural markup, each viewing system could then use different display techniques for each type of structure. For example, emphasized words could be bold or italic, headings could be large, or block quotes could be indented. To keep file sizes down and compatibility up, HTML documents used only the ASCII character set. Most important, the markup tags did not attempt to tell each terminal how to do its job--they simply identified the logical structure of a document. The Web's designers assumed that each receiving system would decide how best to display each tagged element. This approach is illustrated on the Early HTML Approach Diagram. Early HTML Approach Workarounds, Kludges, and Hacks Of course, the Web did not stay a text-only medium for long. The first graphical browsers for personal computers (PCs) opened the Web to millions of home users, and gave graphic designers an amazing new toy. They quickly discovered what we just discussed: HTML was never meant to create visually pleasing layouts. However, that did not stop them from making it work somehow. Soon graphic designers were using tables to create columns, margins, and layouts that wrapped text around graphics. They used invisible GIF images as spacers and props to force other elements into position. To override each browser's default text display settings, they made heavy use of the <FONT> tag to control the font, size, and color of text. Today, a Web designer's toolbox is stuffed with workarounds, tricks, and proprietary elements, most of which are designed to make HTML do things it was not designed for. The resulting code is dense, difficult to read, and overly complex. Although the Web has become a much more interesting place, from an information systems perspective, it is a mess. Separating Content From Appearance CSS offer a compromise that allows HTML to get back to doing its rightful job. The key to CSS is the principle of separating a document's content from its appearance, which is what HTML's designers had in mind from the start. However, instead of a document's appearance being controlled by the browser's default display settings, CSS allows Web designers to create their own settings. These settings are then stored in a separate file, or style sheet, which is downloaded with a Web page, as shown on the Cascading Style Sheets Diagram. Cascading Style Sheets CSS promises to give designers greater control over page appearance. When excessive and redundant formatting code is gone, page files will be smaller (and load faster). By centralizing all formatting information in a few style sheets, it will become much easier and faster to update a site's look. However, there are other important reasons to use CSS to separate content from appearance. Accessibility The Web has opened the world to millions of people with disabilities. However, many of these users, particularly those with visual impairments, are still shut off from some of the Web's most useful and enjoyable content. The reason is that adaptive technologies for the blind, such as voice and Braille "readers," often cannot find the content hidden in a maze of page-layout tables and graphics. Cleaner, simpler files are not just easier for the developer, they are easier for everyone. Dynamic Content Database-driven Web sites force developers to separate content from appearance, because dynamic sites work like a mail-merged form letter. Raw data is pulled from a database, and then inserted into a Web page that applies appearance formatting to the data. As sites become more dynamic, they will rely more heavily on flexible page designs that handle appearance and content separately. How Style Sheets Work Before we get into the details of CSS, a quick demonstration will provide a taste of its advantages. First, let us review how "regular" HTML handles text formatting. Create this file, save it as plain text, and name it OLD_HTML.HTM: <HTML> <HEAD> <TITLE>Old-Fashioned Text</TITLE> </HEAD> <BODY> <BASEFONT FACE="Verdana, Helvetica, Arial" COLOR="blue" SIZE=2> <H1><FONT FACE="Verdana, Helvetica, Arial, sans-serif" COLOR="red" SIZE=4>Old-Fashioned HTML Text Formatting </FONT></H1> <P>This is how we formatted text back in the <FONT FACE="Verdana, Helvetica, Arial, sans-serif" COLOR="black" SIZE=3>dark days</FONT> before Cascading Style Sheets.</P> <P>If we wanted <B>bold text</B> to look different than <STRONG>strong text</STRONG>, it was hard to specify that<FONT FACE="Verdana, Helvetica, Arial, sans-serif"> <I>strong text should be italic.</I></FONT></P> </BODY> </HTML> In your browser, it should look something like this: Now let us see how a style sheet can improve matters. In this example, you will create two files. For now, just enter them exactly as they appear below; we will discuss them in detail later. First, create the following new HTML file, save it as plain text, and name it NEW_HTML.HTM: <HTML> <HEAD> <TITLE>New, Improved Text</TITLE> <LINK rel=stylesheet a href="new_HTML.css" type="text/css"> </HEAD> <BODY> <H1>New, Improved CSS Text Formatting</H1> <P>Cascading Style Sheets lets us format each HTML tag. </P> <P>Now if we want <B>bold text</B> to look different than<STRONG>strong text</STRONG>, we can just set it up in the style sheet.</P> <H2>The best thing is that we format each tag only once!</H2> </BODY> </HTML> Next, create a style sheet file, separate from the HTML file. Save the following file as plain text, and name it NEW_HTML.CSS: H1 { color: red; font-size: 24px; font-family: verdana, helvetica, arial, sans-serif } H2 { color: purple; font-size: 18px; font-style: italic; font-family: verdana, helvetica, arial, sans-serif } P { color: black; font-size: 16px; font-family: verdana, helvetica, arial, sans-serif } STRONG { color: green; font-style: italic; font-family: times, serif } B { color: blue; font-weight: bold } Make sure both files are in the same folder, then open NEW_HTML.HTM in your browser. It should look like this: In this exercise, you removed most of the text formatting instructions from the HTML document, and moved the instructions to a separate style sheet file. The <LINK> tag in the HTML file points to the style sheet, thus the browser knows where to find the formatting information. What's in a Rule Each line in the style sheet is called a rule, and each rule formats one HTML tag. The rules tell the browser how to display each HTML tag in the style sheet. When an HTML document is linked to a style sheet, all of its tags receive the formatting defined in the style sheet's rules. The browser uses its default settings to display any tags in the HTML document that do not have rules in the style sheet. A rule consists of two parts: Selector-- The HTML tag the rule defines. For example, "H1" is a selector; however, a selector may include more than one tag. In the next lesson, you will see how this can be useful. Declaration --The instructions, between the curly braces {}, that make up the rule. A declaration includes pairs of properties (such as "font-family") and values (such as "Arial"). A declaration may contain as many propertyvalue pairs as necessary. Each property-value pair is separated by a semicolon. The rules in this style sheet are very simple, because it is a quick example. However, a rule can contain any number of attributes that control an element's appearance and behavior. New Features in Cascading Style Sheets (CSS) Most of this style sheet's formatting information is similar to regular HTML. However, notice one important difference in the font-size attribute: "24px" means text 24 pixels high. Unlike HTML, which offers only seven fixed text sizes, CSS lets you set the exact size of text using almost any measurement unit: pixels, points, millimeters, centimeters, inches, or picas. That, by itself, can be enough of a reason to start using CSS right now. In addition to precise text size control, the CSS standard specifies a wide range of layout control features, such as: Precise positioning of elements, relative to the page Separate backgrounds for each element Word spacing and line spacing (leading) Text margins without using tables Borders around elements (a box around text is an attribute of the text) Text wrap around graphics Rich variety of styles for numbered and bulleted lists (including graphics as bullets) That's the good news. If CSS includes all these great features, why aren't Web designers rushing to use it? The answer leads us to the bad news. Putting Style in Your Pages The preceding exercise placed style information in a separate file. There are four methods available to apply style definitions to elements in a document as follows: Inline Styles for Single Elements Inline styles are embedded into the tag of each individual element, similar to the "old-fashioned" HTML example above. Therefore, each style definition only applies to a single element. An inline style definition looks something like the example below. Code Bit: <BODY> <H1 style="color: blue; font-family: arial; font-size: 24px" >This is an Inline style</H1> <P style="font-family: arial; font-size: 16px">Inline styles are good for local overrides, but don't overdo it.</P> </BODY> Inline styles can be useful for localized changes or one-element modifications. Extensive use, however, puts you right back where you are now, with ungainly code and difficult sitewide modifications. Embedded Styles for Single Pages When a style sheet is embedded in a document, the style information is contained within special <STYLE> tags between the <HEAD> tags. Embedded style definitions govern the appearance of tags throughout the entire page. On a large page, it is a real time saver to be able to define the look of each tag once, and then use the tags without individual modifications. The example below has the same effect of the inline example above; however, this code is easier to read and maintain. Code Bit: <HEAD> <STYLE type="text/css"> <!-- Important: Put a comment here to make older browsers ignore the style code! H1 { color: blue; font-family: arial; font-size: 24px } P { font-family: arial; font-size: 16px } </STYLE> </HEAD> <BODY> <H1>This is Real an Embedded style</H1> <P>Embedded styles apply to an entire Web page, not just individual elements.</P> </BODY> TIP: The Style Type tag defines the Multipurpose Internet Mail Extension (MIME) type, so that legacy browsers ignore the style information. Using an HTML comment to "hide" the information will ensure that even the oldest browsers do not attempt to render the code in the page itself. If you do not include both of these elements, CSS-challenged browsers will display your style definition code at the top of your Web page, a potentially embarrassing situation. In addition, do not put a space between any CSS value and its unit of measure. For example, in the inline example above, font size is specified as "24px" not "24 px." CSS ignores any rule with a space between a value and unit. Although an improvement over inline styles, embedded style sheets are still difficult to update on a site-wide basis, because the designer must change each page. To ease the designer's workload, it would be best to maintain all of a site's style information in a single file. In this case, a developer could change the look of an entire site by modifying just one style sheet document. Linked style sheets provide this flexibility. Linked Styles for Multiple Pages The hands-on exercise above, using the NEW_HTML.HTM and NEW_HTML.CSS files, is an example of linking an HTML file to an external style sheet. As you saw in that example, a single line of code is all you need to link a style sheet to a page. A style sheet may have any file name; it is only important that the HTML page correctly reference the file name in the <LINK> tag. In the exercise, we placed both CSS and HTML files in the same directory; however, this is not absolutely necessary. CSS follows the same rules HTML uses for absolute and relative linking. When a Web page is linked to a style sheet, a browser requests the style sheet along with the page. The browser reads both the page and style sheet, then applies the style rules when displaying the page elements. The only drawback to this method is that the browser must read an extra file when opening a Web page. However, this is not a real problem. Style sheets are extremely small ASCII text files that load quickly, browsers often cache them (so each style sheet only loads once) and, as a <HEAD> item, a style sheet loads before the rest of the page. Imported Styles for Single-Page Modifications Importing a style sheet is similar to linking, because the designer creates an external style sheet file. However, an HTML file can apply an imported style sheet in combination with embedded styles in that page. In practice, this means that localized (page-specific) information can be contained as embedded rules to override the external style sheet on a page-by-page basis. This offers more flexibility than the linked style sheet. However, with proper planning and an extensive library of style sheets, it is usually unnecessary. The following code fragment will change the example file NEW_HTML.HTM so that it imports the style sheet instead of linking to it. The embedded style rule for <H1> overrides the <H1> style in the external sheet. Code Bit: <HEAD> <STYLE type="text/css"> <!-- Comment to hide styles from CSS-challenged browsers. @import url(new_HTML.css); H1 { color: red; font-size: 20px; font-family: times } </STYLE> <TITLE>New, Improved Text</TITLE> </HEAD> Tip: In the @import line above, do not insert a space between "url" and "(new_HTML.css)." A space in this position will cause an import to fail. Understanding the Cascade Thus far, we have seen that embedded style rules can override linked styles. The relationship is part of a system called the cascade, shown on the Cascade Hierarchy Diagram. A cascade tells a browser how to evaluate the relative importance of external style sheets, embedded styles, and inline styles. Cascade Hierarchy In the above diagram, a formatting method overrides all methods beneath it. Therefore, if a Web page is linked to an external style sheet, the external rules control all elements on that page except any elements individually formatted using inline rules. For example, consider an embedded definition that tells the browser to render everything within the <P> tags as Arial, 16 pixels tall. The same page also contains an inline style that defines an individual <P> element as Arial, 12 pixels tall. The browser will render the inline definition, because it ranks higher in the cascade. HTML's Place in the Cascade The CSS standard says that any style sheet must override any HTML formatting in a document; in theory, we should be able to add a style sheet to an HTML page without removing old HTML tag formatting. Unfortunately, both Microsoft Internet Explorer and Netscape Communicator ignore this part of the specification. In the current versions of the browsers, HTML formatting overrides any CSS formatting. The Viewer's Place in the Cascade Early browsers allowed each user to define the appearance of each HTML tag. This was very helpful to visually impaired users, who often used these settings to increase text size and color contrast. However, this ability created inconsistent page displays that quickly drove designers to override browser settings with the <FONT> tag. CSS has returned some viewing control, by allowing users to define their own default style sheets. However, a Web author's style rules always override a user's, unless the user's style rules include the special declaration "! important." For example: P { font-size: 16pt ! important; line-height: 150% ! important } A user's rule with an "! important" declaration overrides a Web author's rule with a normal declaration. However, an author's rule with an "! important" declaration overrides a reader's rule with an "! important" declaration. In other words, the CSS cascade is biased in favor of Web developers. To ensure that their style rules always "win," developers can simply insert "! important" after every property in every rule. However, many developers define "winning" as providing the broadest accessibility for the greatest number of users; those developers respect user-defined style sheets by avoiding the "! important" declaration.