NP HTML-CSS Tutorial 2 Replacement (3) PDF
Document Details
Tags
Summary
This document is a tutorial on HTML and CSS, specifically focusing on getting started with CSS. It covers topics like color values, style rules, selectors, and different types of style sheets. It also includes a case study on designing a website for a fitness club.
Full Transcript
TuTorial 2 O b j e c t i ves Getting Started Session 2.1 Explore the history of CSS Study different types of style with CSS sheets Designing a Website for a Fitness C...
TuTorial 2 O b j e c t i ves Getting Started Session 2.1 Explore the history of CSS Study different types of style with CSS sheets Designing a Website for a Fitness Club Explore style precedence and inheritance Apply colors in CSS Case | Tri and Succeed Sports Session 2.2 Use contextual selectors Alison Palmer runs Tri and Succeed Sports, an athletic club in Work with attribute selectors Austin, Texas that specializes in coaching men and women aspiring Apply text and font styles to compete in triathlons and other endurance sports. The center Use a web font provides year-round instruction in running, swimming, cycling, and Session 2.3 general fitness with one-on-one and group training classes. Alison Define list styles has asked you to work on the company’s new website. Work with margins and Alison designed the original Tri and Succeed Sports website several padding space years ago but she now feels that the site needs a makeover. She Use pseudo-classes and wants a new design that uses color and interesting typography to pseudo-elements Insert page content with CSS create visual interest and impact. She wants you to use CSS to help give the website a new look. STarTing DaTa FileS html02 tutorial review case1 case2 tss_bike_txt.html tss_coach_txt.html ph_plays_txt.html mw_tour_txt.html tss_home_txt.html coach_styles_txt.css ph_styles_txt.css mw_styles_txt.css tss_run_txt.html + 8 files + 8 files + 2 files tss_swim_txt.html tss_styles_txt.css + 8 files case3 case4 demo cw_class_txt.html lake_home_txt.html demo_css.html cw_styles_txt.css lake_styles_txt.css demo_color_names.html + 3 files + 7 files + 3 files HTML 83 HTML 84 HTML and CSS | Tutorial 2 Getting Started with CSS session 2.1 visual Overview: The @charset rule specifies the character encoding used in the style sheet file. Style comments provide information about the style sheet. The HSL color value defines a color based on its hue, saturation, and lightness. A style rule sets the display properties of a page element. The RGB color value defines a color based on the mixture of red, green, and blue colors. CSS supports 147 color names. The style property The selector defines specifies what aspect of what element or elements the selector to modify. are affected by the rule. The color property sets the text color for the selected elements. © 2016 Cengage Learning; The background-color © Ysbrand Cosijn/Shutterstock.com; property sets the © Charles T. Bennett/Shutterstock.com; background color for the © ostill/Shutterstock.com; selected elements. © Monkey Business Images/Shutterstock.com Tutorial 2 Getting Started with CSS | HTML and CSS HTML 85 css styles and colors The browser window The h1 headings appear background color is set to the in white on a dark orange color value hsl(27, 73%, 72%) background as specified using the html style rule. by the h1 style rule. The h2 headings appear in white on a light orange background as specified by the h2 style rule. Page body background Page text is set to the color is set to ivory using color value rgb(91, 91, 91). the body style rule. HTML 86 HTML and CSS | Tutorial 2 Getting Started with CSS Introducing CSS One of the important principles discussed in the previous tutorial was that HTML does not define how a document should be displayed; it only defines the document’s structure and content. The appearance of the page is determined by one or more style sheets written in the Cascading Style Sheets (CSS) language. Starting with this tutorial, you’ll learn how to write your own CSS style sheets. The CSS specifications are maintained by the same World Wide Web Consortium (W3C) that defines the standards for HTML. As with HTML, the CSS language has gone through several versions, the latest of which is CSS Version 3, more commonly known as css3. CSS3 is not based on a single specification but rather is built upon several modules, where each module is focused on a separate design topic. At the time of this You can research the writing, there were over 50 CSS3 modules with each module experiencing a different support for CSS by level of browser support. The W3C continues to expand the scope of the language, browser version at which means that many new design features are still at the stage where few, if any, www.caniuse.com. browsers support them. In these tutorials, you’ll focus mostly on CSS features that have near-universal support among current browsers. However, you’ll also examine workarounds to support older browsers and study ways to accommodate the difference between browsers in how they implement CSS designs. Types of Style Sheets A website’s design is usually not the product of a single style sheet; rather, it is a combination of styles starting from the browser style sheet and then superseded by the user-defined style sheet, external style sheets, embedded style sheets, and concluding with inline styles (see Figure 2-1.) Let’s examine each of these style sources in more detail. Figure 2-1 Hierarchy of styles inline styles embedded styles external styles user-defined styles browser styles © 2016 Cengage Learning Tutorial 2 Getting Started with CSS | HTML and CSS HTML 87 The first styles to be processed are the browser styles or user agent styles, which are the styles built into the browser itself. In the absence of competing styles from other style sheets, a browser style is the one applied to the web page. The next styles to be processed are the user-defined styles, which are styles defined by the user based on the settings he or she makes in configuring the browser. For example, a user with a visual impairment could alter the browser’s default settings to display text with highly contrasting colors and a large font size for improved readability. Any user-defined style has precedence over its browser style counterpart. User-defined styles can be superseded by external styles, which are the styles that the website author creates and places within a CSS file and links to the page. You used external style sheets in the last tutorial when you linked the Curbside Thai website to a collection of CSS files. As you saw in that tutorial, multiple documents can access the same style sheet, which makes it easy to apply a common design to an entire website. Above the external styles in the hierarchy of style sheets are embedded styles, which are the styles added to the head of an HTML document. Embedded styles only apply to the HTML document in which they are created and they are not accessible to other documents in the website, but they do override any styles in an external style sheet. Finally, at the highest order of precedence are inline styles, which are added as element attributes within an HTML document and thus apply to that element alone. Embedded styles and inline styles are not considered best practice and their use should be avoided because they violate the basic tenets of HTML, which is that HTML should only describe the content and structure of the document and that design styles should be placed outside of the HTML code. The overall design of a web page is based on a combination of the styles from these different sources. Some of the styles might originate from the browser style sheet while others will be defined in an external style sheet or an embedded style sheet. Part of the challenge of CSS is determining how styles from these different style sheets interact to determine the page’s final appearance. Viewing a Page Using Different Style Sheets You’ll start your work on the Tri and Succeed Sports website by viewing how the home page appears when it is rendered in the default styles of the style sheet built into your browser. To view the Tri and Succeed Sports home page: ◗ 1. Use your editor to open the tss_home_txt.html file from the html02 tutorial folder. Enter your name and the date in the comment section of the file and save the document as tss_home.html. ◗ 2. Take some time to scroll through the document to become familiar with its content and structure. ◗ 3. Open the tss_home.html page in your browser. Part of the appearance of the page is shown in Figure 2-2. HTML 88 HTML and CSS | Tutorial 2 Getting Started with CSS Figure 2-2 the tss home page rendered using only the browser style sheet heading displayed in a larger bold font hypertext list items displayed displayed with a solid circle in blue strong text displayed in bold © 2016 Cengage Learning; © Ysbrand Cosijn/Shutterstock.com; © Charles T. Bennett/Shutterstock.com; © ostill/Shutterstock.com; © Monkey Business Images/Shutterstock.com Trouble? Depending on your browser’s style sheet, your page might not exactly resemble the one shown in Figure 2-2. The browser style sheet applies a few specific styles to the page, including adding solid circles to the navigation list items, as well as displaying hypertext in blue, headings in a large bold font, and strong text in a bold font. However the page layout is difficult to read. Alison has an external style sheet containing styles that will present this page in a more pleasing three-column layout. Link this page now to her style sheet file and then reload the document in your browser to view the impact on the page’s appearance. Tutorial 2 Getting Started with CSS | HTML and CSS HTML 89 To change the layout of the TSS home page: ◗ 1. Return to the tss_home.html file in your HTML editor and add the following link element to the head section directly after the title element: Figure 2-3 highlights the newly added code in the document. Figure 2-3 Linking to the tss_layout.css file rel attribute indicates that the file is a style sheet filename of style sheet ◗ 2. Save your changes to the file and then reopen the tss_home.html file in your browser. Figure 2-4 shows the appearance of the page using the layout styles defined in the tss_layout.css file. Figure 2-4 the tss home page using the tss_layout.css style sheet © 2016 Cengage Learning; © Ysbrand Cosijn/Shutterstock.com; © Charles T. Bennett/Shutterstock.com; © ostill/Shutterstock.com; © Monkey Business Images/Shutterstock.com The tss_layout.css file controls the placement of the page elements but not their appearance. The colors, fonts, and other design styles are still based on the browser style sheet. HTML 90 HTML and CSS | Tutorial 2 Getting Started with CSS Exploring Style Rules If the element tag is the building block of the HTML file, then the style rule, which defines the styles applied to an element or group of elements, is the building block of the CSS style sheet. Style rules have the general form selector { property1: value1; property2: value2;... } where selector identifies an element or a group of elements within the document and the property: value pairs specify the style properties and their values applied to that element or elements. For example, the following style rule has a selector of h1 to match all h1 elements in the document and it has property: value pairs of color: red and text-align: center that tell the browser to display all h1 headings in red and centered on the page: h1 { color: red; text-align: center; } Selectors can also be entered as comma-separated lists as in the following style rule that displays both h1 and h2 headings in red: h1, h2 { color: red; } Like HTML, CSS ignores the use of white space, so you can also enter this style more compactly as follows: h1, h2 {color: red;} Writing a style rule on a single line saves space, but entering each style property on a separate line often makes your code easier to read and edit. You will see both approaches used in the CSS files you encounter on the web. Browser Extensions In addition to the W3C-supported style properties, most browsers supply their own extended library of style properties, known as browser extensions. Many of the styles that become part of the W3C specifications start as browser extensions and for older browser versions, sometimes the only way to support a particular CSS feature is through a browser extension tailored to a particular browser. Browser extensions are identified through the use of a vendor prefix, which indicates the browser vendor that created and supports the property. Figure 2-5 lists the browser extensions you’ll encounter in your work on web design. Tutorial 2 Getting Started with CSS | HTML and CSS HTML 91 Figure 2-5 vendor prefixes for browser extensions Vendor Prefix Rendering Engine Browsers -khtml- KHTML Konqueror -moz- Mozilla Firefox, Camino -ms- Trident Internet Explorer -o- Presto Opera, Nintendo Wii browser -webkit- WebKit Android browser, Chrome, Safari For example, one of the more recent style features added to CSS3 is the layout style to display content in separate columns. The number of columns is indicated using the column-count property. To apply this style in a way that supports both older and current browsers, you would include the browser extensions first followed by the most current CSS specification: article { -webkit-column-count: 3; -moz-column-count: 3; column-count: 3; } In general, browsers process style properties in the order they’re listed, ignoring those properties they don’t recognize or support, so you always want the most current specifications listed last. Embedded Style Sheets The style rule structure is also used in embedded style sheets and inline styles. Embedded styles are inserted directly into the HTML file as metadata by adding the following style element to the document head style rules where style rules are the different rules you want to embed in the HTML page. For example, the following embedded style applies the same style rules described previously to make all h1 headings in the current document appear in red and centered: h1 { color: red; text-align: center; } Remember that, when all else is equal, the style that is loaded last has precedence over styles defined earlier. In the following code, the browser will load the embedded style sheet last, giving it precedence over the style rules in the tss_styles.css file. style rules HTML 92 HTML and CSS | Tutorial 2 Getting Started with CSS If the order of the link and style elements is reversed, the styles from the tss_styles.css file are loaded last and given precedence. To avoid confusion, always place your embedded styles after any links to external style sheet files so Inline Styles that the embedded styles The very last styles to be interpreted by the browser are inline styles, which are styles always have precedence. applied directly to specific elements using the following style attribute content where the property: value pairs define the styles, which are applied directly to that element. Thus, the following inline style sets the appearance of the h1 heading to red text centered on the page: Tri and Succeed Sports This style applies only to this particular h1 heading and not to any other h1 heading on the page or in the website. The advantage of inline styles is that it is clear exactly what page element is being formatted; however, inline styles are not recommended in most cases because they make changing designs tedious and inefficient. For example, if you used inline styles to format all of your headings, you would have to locate all of the h1 through h6 elements in all of the pages within the entire website and add style attributes to each tag. This would be no small task on a large website containing hundreds of headings spread out among dozens of pages. Likewise, it would be a nightmare if you had to modify the design of those headings at a later date. Thus, the recommended practice is to always use external style sheets that can be applied across pages and page elements. Style Specificity and Precedence With so many different style rules to be applied to the same document, there has to be an orderly method by which conflicts between those different rules are resolved. You’ve already learned that the style that is defined last has precedence, but that is not the whole story. Another important principle is that the more specific style rule has precedence over the more general style rule. Thus, a rule applied to a specific paragraph takes precedence over a rule applied to the entire page, and a rule applied to a section of text within that paragraph takes precedence over the rule for the paragraph. For example, in the following style rules, the color of the text in all paragraphs is set to red, taking precedence over the color black applied to the rest of the text in the page: p {color: red;} body {color: black;} Note that specificity is only an issue when two or more styles conflict, as in the example above. When the style rules involve different properties (such as color and size), there is no conflict and both rules are applied. If two rules have equal specificity and thus, equal importance, then the one that is defined last has precedence. Tutorial 2 Getting Started with CSS | HTML and CSS HTML 93 Style Inheritance An additional factor in how an element is rendered is that properties are passed from Not all properties are a parent element to its children in a process known as style inheritance. Thus, the inherited; for example, a following style rule sets the color of article text to blue and that rule is passed to any style property that defines paragraph, header, footer, or other element nested within that article. In addition, the text color has no meaning text in a paragraph within that article is centered: for an inline image. article {color: blue;} p {text-align: center;} Thus, the final rendering of any page element is the result of styles drawn from rules across multiple style sheets and from properties passed down from one element to another within the hierarchy of page elements. These style sheets and style rules form the “cascade“ of styles in Cascading Style Sheets. Browser Developer Tools If the idea of multiple style sheets and multiple style rules is intimidating, there are In most browsers, you can tools available to help you manage your styles. Most browsers include developer tools quickly access information allowing the designer to view HTML code, CSS styles, and other parts of the web page. about a specific page These developer tools make it easier for the designer to locate the source of a style that element by right-clicking has been applied to a specific page element. the element in the browser Each browser’s developer tools are different and are constantly being updated and window and choosing Inspect Element from the improved with every new browser version. However, to give you the flavor of the tools pop-up menu. you have at your disposal, you’ll examine both the HTML code and the CSS style sheet under the developer tools built into your desktop browser. Note that the figures in the steps that follow use the desktop version of the Google Chrome browser. Accessing the Browser Developer Tools: ◗ 1. Return to the tss_home.html file in your browser. ◗ 2. Press F12 to open the developer tools window. Trouble? If pressing F12 doesn’t open the developer tools, your browser might need a different keyboard combination. In Safari for the Macintosh, you can view the developer tools by pressing ctrl+shift+I or command+option+I. ◗ 3. From the hierarchical list of elements in the web page, click the tag if it is not already selected. Figure 2-6 shows the layout of panes using the developer tools under Google Chrome for the desktop. HTML 94 HTML and CSS | Tutorial 2 Getting Started with CSS Figure 2-6 Developer tools in Google chrome hierarchical list of layout styles elements on the web applied to the page body element diagram of the layout of the body styles applied to the element body element from tss_layout.css style sheet styles applied to the body element the margin style in the from the browser browser style sheet style sheet has been superseded by the margin style in the tss_layout.css style sheet © 2016 Cengage Learning; © Ysbrand Cosijn/Shutterstock.com; © Charles T. Bennett/Shutterstock.com; © ostill/Shutterstock.com; © Monkey Business Images/Shutterstock.com As shown in Figure 2-6, the styles pane lists the styles that have been applied to the body element. Note that the margin property from the browser style sheet has been crossed out, indicating that this browser style has been superseded by a style defined in the external style sheet. Trouble? Every browser has a different set of developer tools and configurations. Your tools might not resemble those shown in Figure 2-6. ◗ 4. Take some time to explore the content and styles used in the other page elements by selecting the elements tags from the hierarchical list of elements. ◗ 5. Press F12 again to close the developer tools window. Trouble? In Safari, you can close the developer tools by pressing ctrl+shift+I or by command+option+I. In this and future tutorials, you may find that your browser’s developer tools are a great aid to working through your website designs. Most developer tools allow the user to insert new style rules in order to view their immediate impact on the page’s appearance; however, these modifications are only applied during the current session and are not saved permanently. So, once you find a setting that you want to use, you must enter it in the appropriate style sheet for it to take effect permanently. Tutorial 2 Getting Started with CSS | HTML and CSS HTML 95 Defining an !important Style INSIGHT You can override the style cascade by marking a particular property with the following !important keyword: property: value !important; The following style rule sets the color of all h1 headings to orange; and because this property is marked as important, it takes precedence over any conflicting styles found in other style sheets. h1 {color: orange !important;} The !important keyword is most often used in user-defined style sheets in which the user needs to substitute his or her own styles in place of the designer’s. For example, a visually impaired user might need to have text displayed in a large font with highly contrasting colors. In general, designers should not use the !important keyword because it interferes with the cascade order built into the CSS language. Creating a Style Sheet Now that you’ve reviewed some history and concepts behind style sheets, you’ll start creating your own. You should usually begin your style sheets with comments that document the purpose of the style sheet and provide information about who created the document and when. Writing Style Comments Style sheet comments are entered as where comment is the text of the comment. Because CSS ignores the presence of white space, you can insert your comments on a single line to save space as: Create a style sheet file now, placing a comment with your name and the current date at the top of the file. Writing a Style Comment: ◗ 1. Use your editor to open the tss_styles_txt.css file from the html02 tutorial folder. ◗ 2. Within the comment section at the top of the file, enter your name following the Author: comment and the date following the Date: comment. ◗ 3. Save the file as tss_styles.css. ◗ 4. Return to the tss_home.html file in your HTML editor and add the following link element directly before the closing tag. ◗ 5. Close the tss_home.html file, saving your changes. HTML 96 HTML and CSS | Tutorial 2 Getting Started with CSS Defining the Character Encoding As with HTML files, it is a good idea in every CSS document to define the character encoding used in the file. In CSS, you accomplish this using the following @charset rule @charset "encoding"; where encoding defines the character encoding used in the file. Add the @charset rule to the tss_styles.css style sheet file now, specifying that the UTF-8 character set is used in the CSS code. To indicate the character encoding: ◗ 1. Return to the tss_styles.css file in your editor. ◗ 2. Directly above the initial comment section, insert the line: @charset "utf-8";. Figure 2-7 highlights the new code in the style sheet. Figure 2-7 Adding the @charset rule and style comments the charset rule defines the character encoding used in the style sheet CSS comments provide information about the style sheet author name and current date Note that only one @charset rule should appear in a style sheet and it should always precede any other characters, including comments. ◗ 3. Save your changes to the file. Importing Style Sheets The @charset rule is an example of a css at-rule, which is a rule used to send The @import statement directives to the browser indicating how the contents of the CSS file should be must always come before interpreted and parsed. Another at-rule is the following @import used to import the any other style rules in the contents of a style sheet file style sheet. @import url(url); where url is the URL of an external style sheet file. The @import is used to combine style rules from several style sheets into a single file. For example, an online store might have one style sheet named basic.css containing all of the basic styles used in every web page and another style sheet Tutorial 2 Getting Started with CSS | HTML and CSS HTML 97 named sales.css containing styles used with merchandise-related pages. The following code imports styles from both files: @import url(company.css); @import url(support.css); Using multiple @import rules in a CSS file has the same impact as adding multiple link elements to the HTML file. One advantage of the @import rule is that it simplifies your HTML code by placing the decision about which style sheets to include and exclude in the CSS file rather than in the HTML file. Working with Color in CSS The first part of your style sheet for the Tri and Succeed Sports website will focus on color. If you’ve worked with graphics software, you’ve probably made your color selections using a graphical interface where you can see your color options. Specifying color with CSS is somewhat less intuitive because CSS is a text-based language and requires colors to be defined in textual terms. This is done through either a color name or a color value. Color Names You’ve already seen from previous code examples that you can set the color of page You can view the complete text using the color property along with a color name such as red, blue, or black. CSS list of CSS color names by supports 147 color names covering common names such as red, green, and yellow to opening the demo_color_ more exotic colors such as ivory, orange, crimson, khaki, and brown. names.html file in the html02 demo folder. Written Communication: Communicating in Color PROSKILLS Humans are born to respond to color. Studies have shown that infants as young as two months prefer bright colors with strong contrast to drab colors with little contrast, and market research for clothing often focuses on what colors are “in“ and what colors are passé. Your color choices can impact the way your website is received so you want to choose a color scheme that is tailored to the personality and interests of your target audience. Color can evoke an emotional response and is associated with particular feelings or concepts, such as red—assertive, powerful, sexy, dangerous pink—innocent, romantic, feminine black—strong, classic, stylish gray—business-like, detached yellow—warm, cheerful, optimistic blue—consoling, serene, quiet orange—friendly, vigorous, inviting white—clean, pure, straightforward, innocent If your website will be used internationally, you need to be aware of how cultural differences can affect your audience’s response to color. For instance, white, which is associated with innocence in Western cultures, is the color of mourning in China; yellow, which is considered a bright, cheerful color in the West, represents spirituality in Buddhist countries. HTML 98 HTML and CSS | Tutorial 2 Getting Started with CSS RGB Color Values Because a palette of 147 color names is extremely limited for graphic design and color names can be constricting (how do you name a color that is slightly redder than ivory with a tinge of blue?), CSS also supports color values, in which the color is given by an exact numeric representation. CSS3 supports two types of color values: RGB values and HSL values. RGB color values are based on classical color theory in which all colors are determined by adding three primary colors—red, green, and blue—at different levels of intensity. For example, adding all three primary colors at maximum intensity produces the color white, while adding any two of the three primary colors at maximum intensity produces the trio of complementary colors—yellow, magenta, and cyan (see Figure 2-8). Figure 2-8 color addition in the RGb color model red magenta yellow white blue green cyan © 2016 Cengage Learning Varying the intensity of the three primary colors extends the palette to other colors. Orange, for example, is created from a high intensity of red, a moderate intensity of green, and a total absence of blue. CSS represents these intensities mathematically as a set of numbers called an RGb triplet, which has the format rgb(red, green, blue) where red, green, and blue are the intensities of the red, green, and blue components of the color. Intensities range from 0 (absence of color) to 255 (maximum intensity); thus, the color white has the value rgb(255, 255, 255), indicating that red, green, and blue are mixed equally at the highest intensity, and orange is represented by rgb(255, 165, 0). RGB triplets can describe 2563 (16.7 million) possible colors, which is a greater number of colors than the human eye can distinguish. Tutorial 2 Getting Started with CSS | HTML and CSS HTML 99 RGB values are sometimes expressed as hexadecimal numbers where a hexadecimal number is a number expressed in the base 16 numbering system rather than in the commonly used base 10 system. In base 10 counting, numeric values are expressed using combinations of 10 characters (0 through 9). Hexadecimal numbering includes these ten numeric characters and six extra characters: A (for 10), B (for 11), C (for 12), D (for 13), E (for 14), and F (for 15). For values above 15, you use a combination of those 16 characters. For example, the number 16 has a hexadecimal representation of 10, and a value of 255 has a hexadecimal representation of FF. The style value for color represented as a hexadecimal number has the form #redgreenblue where red, green, and blue are the hexadecimal values of the red, green, and blue components. Therefore, the color yellow could be represented either by the RGB triplet rgb(255,255,0) or more compactly as the hexadecimal #FFFF00 Most HTML editors and graphic programs provide color picking tools that allow the user to choose a color and then copy and paste the RGB or hexadecimal color value. Hexadecimal color values have the advantage of creating smaller style sheets, which can be loaded faster—an important consideration for mobile devices. However, for others viewing and studying your style sheet code, they are more difficult to interpret than RGB values. Finally you can enter each component value as a percentage, with 100% representing the highest intensity. In this form, you would specify the color orange with the following values rgb(100%, 65%, 0%) which is equivalent to the rgb(255, 165, 0) value described above. HSL Color Values HSL color values were introduced in CSS3 and are based on a color model in which each color is determined by its hue, saturation, and lightness. Hue is the tint of the color and is usually represented by a direction on a color wheel. Hue values range from 0° up to 360°, where 0° matches the location of red on the color wheel, 120° matches green, and 240° matches blue. saturation measures the intensity of the chosen color and ranges from 0% (no color) up to 100% (full color). Finally, lightness measures the brightness of the color and ranges from 0% (black) up to 100% (white). Figure 2-9 shows how setting the hue to 38°, the saturation to 90%, and the lightness to 60% results in a medium shade of orange. HTML 100 HTML and CSS | Tutorial 2 Getting Started with CSS Figure 2-9 Defining the color orange under the HsL color model hsl(38, 90%, 60%) 90% saturation; 60% lightness red= 0° 0% orange at about 38° + 50% + green = 120° 100% blue= 240° 0% 50% 100% hue expressed as degrees saturation varies lightness varies on the color wheel from 0% to 100% from 0% to 100% © 2016 Cengage Learning Color values using the HSL model are described in CSS3 using hsl(hue, saturation, lightness) where hue is the tint of the color in degrees, saturation is the intensity in percent, and lightness is the brightness in percent of the color. Thus, a medium orange color would be represented as hsl(38, 90%, 60%) Graphic designers consider HSL easier to use because it allows them to set the initial color based on hue and then fine-tune the saturation and lightness values. This is more difficult in the RGB model because you have to balance three completely different colors to achieve the right mix. For example, the RGB equivalent to the color orange in Figure 2-9 would be the color value rgb(245, 177, 61); however, it’s not immediately apparent why that mixture of red, green, and blue would result in that particular shade of orange. Defining Semi-Opaque Colors CSS3 introduced opacity to the CSS color models where opacity defines how solid the color appears. The color’s opacity can be specified using either of the following rgba and hsla properties rgba(red, green, blue, opacity) hsla(hue, saturation, lightness, opacity) where opacity sets the opacity of the color ranging from 0 (completely transparent) up to 1.0 (completely opaque). For example, the following style property uses the HSL color model to define a medium orange color with an opacity of 0.7: hsla(38, 90%, 60%, 0.7) The final appearance of a semi-opaque color is influenced by the background color. Displayed against a white background, a medium orange color would appear in a lighter shade of orange because the orange will appear mixed with the background white. Tutorial 2 Getting Started with CSS | HTML and CSS HTML 101 On the other hand, the same orange color displayed on a black background would appear as a darker shade of orange. The advantage of using semi-transparent colors is that it makes it easier to create a color theme in which similarly tinted colors are blended with other colors on the page. Setting Text and Background Colors Now that you’ve studied how CSS works with colors, you can start applying color to some of the elements displayed on the Tri and Succeed Sports website. CSS supports the following styles to define both the text and background color for each element on your page color: color; background-color: color; where color is either a color value or a color name. Alison wants to use an HSL color value (27, 72%, 72%) to set the background of the document to orange and she would like the text of the home page to appear in a medium gray color on an ivory background. The style rules to modify the appearance of these document elements are html { background-color: hsl(27, 72%, 72%); } body { color: rgb(91, 91, 91); background-color: ivory; } The html selector in this code selects the entire HTML document so that any part of the browser window background that is not within the page body will be displayed using the HSL color (27, 72%, 72%). Within the page body, Alison wants the h1 and h2 headings to be displayed in white text on dark and lighter orange colors using the RGB color values (222, 128, 60) and (235, 177, 131) respectively. The style rules are h1 { color: white; background-color: rgb(222, 128, 60); } h2 { color: white; background-color: rgb(235, 177, 131); } Setting Text and Background Color REFERENCE To set the text color of an element, use the following property color: color; To set the background color of an element, use the following property background-color: color; where color is a color name or a color value. HTML 102 HTML and CSS | Tutorial 2 Getting Started with CSS Next, add style rules for text and background colors to the tss_styles.css file. To define background and text colors: Saturation and lightness ◗ 1. Add the following code within the HTML and Body Styles section: values in an hsl color value html { must be expressed as background-color: hsl(27, 72%, 72%); percentages. } body { color: rgb(91, 91, 91); background-color: ivory; } ◗ 2. Add the following style rules within the Heading Styles section: Almost 8% of all men h1 { and 0.5% of all women color: white; have some sort of color background-color: rgb(222, 128, 60); blindness. Because red- green color blindness is } the most common type of color impairment, you h2 { should avoid using red text color: white; on a green background background-color: rgb(235, 177, 131); and vice-versa. } Figure 2-10 highlights the new style rules. Figure 2-10 Adding text and background colors selects the HTML element sets the document background to a medium orange color selects the body element displays page body text in gray on an ivory background selects all h1 headings displays h1 heading text in white on a dark orange background selects all h2 headings displays h2 heading text in white on a medium orange background Tutorial 2 Getting Started with CSS | HTML and CSS HTML 103 ◗ 3. Save your changes to the file and then reload the tss_home.html file in your browser. Figure 2-11 shows the appearance of the page under the new styles. Figure 2-11 text and background colors in the web page white h1 heading text on a dark orange background browser window background is medium orange white h2 heading text on a light orange background © 2016 Cengage Learning; © Ysbrand Cosijn/Shutterstock.com; © Charles T. Bennett/Shutterstock.com; © ostill/Shutterstock.com; page body style shows © Monkey Business Images/Shutterstock.com gray text on an ivory background Trouble? The text of hypertext links in the left column is blue, using the default browser styles applied to hypertext links. You’ll modify these colors later in the tutorial. HTML 104 HTML and CSS | Tutorial 2 Getting Started with CSS Problem Solving: Choosing a Color Scheme PROSKILLS One of the worst things you can do to your website is to associate interesting and useful content with jarring and disagreeable color. Many designers prefer the HSL color system because it makes it easier to select visually pleasing color schemes. The following are some basic color schemes you may want to apply to websites you design: monochrome—a single hue with varying values for saturation and lightness; this color scheme is easy to manage but is not as vibrant as other designs complementary—two hues separated by 180° on the color wheel; this color scheme is the most vibrant and offers the highest contrast and visual interest, but it can be misused and might distract users from the page content triad—three hues separated by 120° on the color wheel; this color scheme provides the same opportunity for pleasing color contrasts as a complementary design, but it might not be as visibly striking tetrad—four hues separated by 90° on the color wheel; perhaps the richest of all color schemes, it is also the hardest one in which to achieve color balance analogic—two hues close to one another on the color wheel in which one color is the dominant color and the other is a supporting color used only for highlights and nuance; this scheme lacks color contrasts and is not as vibrant as other color schemes Once you have selected a color design and the main hues, you then vary those colors by altering the saturation and lightness. One of the great advantages of style sheets is that you can quickly modify your color design choices and view the impact of those changes on your page content. Employing Progressive Enhancement The HSL color you used for the html selector was introduced with CSS3 and thus it is not supported in very old browsers. If this is a concern, you can insert the older style properties first followed by the newer standards. For example, the following style rule sets the background color of the html element to a lighter orange using the RGB value first, and then the equivalent HSL value. html { background-color: rgb(235, 177, 131); background-color: hsl(27, 72%, 72%); } Old browsers that don’t recognize the HSL color value will ignore it and use the RGB value, while browsers that recognize both values will use the one that is defined last, which in this case is the HSL value. This is an example of a technique known as progressive enhancement, which places code conforming to older standards before newer properties, providing support for old browsers but still allowing newer standards and techniques to be used by the browsers that support them. You show Alison the work you’ve done on colors. She’s pleased with the ease of using CSS to modify the design and appearance of elements on the Tri and Succeed Sports website. In the next session, you’ll continue to explore CSS styles, focusing on text styles. Tutorial 2 Getting Started with CSS | HTML and CSS HTML 105 Session 2.1 Quick Check REVIEW 1. What are inline styles, embedded styles, and external style sheets? Which would you use to define a design for an entire web site? 2. What keyword do you add to a style property to override style precedence and style inheritance? 3. Provide the code to enter the style comment “Tri and Succeed Sports Color Styles“. 4. Provide the style rule to display block quote text in red using an RGB triplet. 5. The color chartreuse is located at 90° on the color wheel with 100% saturation and 50% lightness. Provide a style rule to display address text in black with chartreuse as the background color. 6. What is progressive enhancement? 7. Based on the following style rule for paragraph text, which style property will be used by an older browser that supports only CSS2? p { color: rgb(232, 121, 50); color: hsla(23, 80%, 55%, 0.75); } 8. Provide a style rule to display h1 and h2 headings with a background color of yellow (an equal mixture of red and green at highest intensity with no blue) at 70% opacity. HTML 106 HTML and CSS | Tutorial 2 Getting Started with CSS session 2.2 visual Overview: The @font-face rule imports a web font into the style sheet. The font-family property lists the possible fonts used for the element tex t. The em unit is a relative The font-size unit of length that expresses property sets the text a size relative to the font size size in absolute or of the containing element. relative units. The letter-spacing property sets the kerning or space The aside blockquote between letters. selector selects blockquote elements that are descendants of the aside element. The nav > ul selector selects ul elements that are direct children of the nav element. The line-height property sets the height of the lines of text in the element. The text-align property sets the horizontal alignment of the text. © 2016 Cengage Learning; © Monkey Business Images/Shutterstock.com Tutorial 2 Getting Started with CSS | HTML and CSS HTML 107 css typography The h1 heading is displayed in the Quicksand font with a font size of 2.2em and letter spacing of 0.1em. Body text is displayed in a Verdana font. Navigation list is double-spaced with a line height of 2em. Page footer is centered and The h2 headings are displayed displayed in small caps as specified in the Quicksand font with a by the body > footer address font size of 1.5em and letter style rule. spacing of 0.1em. HTML 108 HTML and CSS | Tutorial 2 Getting Started with CSS Exploring Selector Patterns The following style rule matches every h1 element in the HTML document, regardless of the location of the h1 heading: h1 { color: red; } This style rule will match an h1 heading located within a page article in the same way it matches an h1 heading nested within an aside element or the body header or the body footer. Often, however, you will want your style rules to apply to specific elements, such as h1 headings found within articles but not anywhere else. To direct a style rule to specific elements, you’ll use selector patterns to match only those page elements that correspond to a specified pattern. Contextual Selectors The first selector pattern you’ll examine is a contextual selector, which specifies the context under which a particular page element is matched. Context is based on the hierarchical structure of the document, which involves the relationships between a parent element containing one or more child elements and within those child elements several levels of descendant elements. A contextual selector relating a parent element to its descendants has the following pattern parent descendant { styles } where parent is a parent element, descendant is a descendant of that parent and styles are styles applied to the descendant element. For example, the following style rule sets the text color of h1 headings to red but only when those headings are nested within the header element: header h1 { color: red; } As shown in the code that follows, the descendant element does not have to be a direct child of the parent; in fact, it can appear several levels below the parent in the hierarchy. This means that the above style rule matches the h1 element in the following HTML code: Tri and Succeed Sports In this example, the h1 element is a direct child of the div element; but, because it is still a descendant of the header element, the style rule still applies. Contextual selectors follow the general rule discussed in the last session; that is, the more specific style is applied in preference to the more general rule. For instance, the following style rules would result in h1 headings within the section element being displayed in red while all other h1 headings would appear in blue: section h1 {color: red;} h1 {color: blue;} Figure 2-12 describes some of the other contextual selectors supported by CSS. Tutorial 2 Getting Started with CSS | HTML and CSS HTML 109 Figure 2-12 contextual selectors Selector Description * Matches any element elem Matches the element elem located anywhere in the document elem1, elem2, … Matches any of the elements elem1, elem2, etc. parent descendant Matches the descendant element that is nested within the parent element at some level parent > child Matches the child element that is a child of the parent element elem1 + elem2 Matches elem2 that is immediately preceded by the sibling element elem1 elem1 ~ elem2 Matches elem2 that follows the sibling element elem1 To match any element, use the wildcard selector with the * character. For example, the following style rule matches every child of the article element, setting the text color to blue: article > * {color: blue;} sibling selectors are used to select elements based on elements that are adjacent to them in the document hierarchy. The following style rule uses the + symbol to select the h2 element, but only if it is immediately preceded by an h1 element: h1+h2 {color: blue;} On the other hand, the following style rule uses the ~ symbol to select any h2 element that is preceded (but, not necessarily immediately) by an h1 element: h1 ~ h2 {color: blue;} Figure 2-13 provides additional examples of selectors and highlights in red those elements in the document that would be selected by the specified selector. Figure 2-13 contextual selector patterns p article p article > p body body body article aside article aside article aside header p p p h1 p header p p p h1 p header p p p h1 p h1 p p h1 p p h1 p p h1 + p h1 ~ p article > * body body body article aside article aside article aside header p p p h1 p header p p p h1 p header p p p h1 p h1 p p h1 p p h1 p p © 2016 Cengage Learning HTML 110 HTML and CSS | Tutorial 2 Getting Started with CSS Remember that, because of style inheritance, any style applied to an element is passed down the document tree. Thus, a style applied to a header element is automatically passed down to elements contained within that header unless that style conflicts with a more specific style. Using Contextual Selectors REFERENCE To select all elements, use the * selector. To select a single element, use the elem selector, where elem is the name of the element. To select a descendant element, use the parent descendant selector where parent is a parent element and descendant is an element nested within the parent at some lower level. To select a child element, use the parent > child selector. To select a sibling element, elem2, that directly follows elem1, use the elem1 + elem2 selector. To select a sibling element, elem2, that follows, but not necessarily directly elem1, use the elem1 ~ elem2 selector. Now, you’ll create a style rule to change the text color of the customer testimonials on the Tri and Succeed Sports home page to a dark orange using the RGB color value rgb(232, 165, 116). You’ll use a contextual selector to apply the style rule only to block quotes that are descendants of the aside element. To create style rule with a contextual selector: ◗ 1. If you took a break after the previous session, make sure the tss_styles.css file is open in your editor. ◗ 2. Within the Aside and Blockquote Styles section, insert the following style rule: aside blockquote { color: rgb(232, 165, 116); } Figure 2-14 highlights the new style rule for the blockquote element. Figure 2-14 setting the text color of block quotes sets the text color style applies to block to dark orange quotes nested within an aside element ◗ 3. Save your changes to the file and then reload the tss_home.html file in your browser. Verify that the text of the customer quotes appears in orange. Tutorial 2 Getting Started with CSS | HTML and CSS HTML 111 Attribute Selectors Selectors also can be defined based on attributes and attribute values within elements. Two attributes, id and class, are often key in targeting styles to specific elements. Recall that the id attribute is used to identify specific elements within the document. To apply a style to an element based on its id, you use either the selector #id or the selector elem#id where id is the value of the id attribute and elem is the name of the element. Because ids are supposed to be unique, either form is acceptable but including the element name removes any confusion about the location of the selector. For example, the selector for the following h1 heading from the HTML file Tri and Succeed Sports can be entered as either #title or h1#title in your CSS style sheet. Because no two elements can share the same ID, HTML uses the class attribute to identify groups of elements that share a similar characteristic or property. For example, the following h1 element and paragraph element both belong to the intro class of elements: Tri and Succeed Sports … To select an element based on its class value, use the selector elem.class where class is the value of the class attribute. Thus the following style rule displays the text of h1 headings from the intro class in blue: h1.intro {color: blue;} To apply the same style rule to all elements of a particular class, omit the element An element can belong name. The following style rule displays the text of all elements from the intro class in to several classes by blue: including the class names in a space-separated list in.intro {color: blue;} the class attribute. While id and class are the most common attributes to use with selectors, any attribute or attribute value can be the basis for a selector. Figure 2-15 lists all of the CSS attribute selector patterns based on attributes and attribute values. HTML 112 HTML and CSS | Tutorial 2 Getting Started with CSS Figure 2-15 Attribute selectors Selector Selects Example Selects elem#id Element elem with the ID h1#intro The h1 heading with the value id id intro #id Any element with the ID #intro Any element with the value id id intro elem.class All elem elements with p.main All paragraphs belonging the class attribute value to the main class class.class All elements with the class.main All elements belonging value class to the main class elem[att] All elem elements a[href] All hypertext elements containing the att containing the href attribute attribute elem[att=”text”] All elem elements a[href=”top.html”] All hypertext elements whose att attribute whose href attribute equals text equals top.html elem[att~=”text”] All elem elements a[rel~=”glossary”] All hypertext elements whose att attribute whose rel attribute contains the word text contains the word glossary elem[att|=”text”] All elem elements whose p[id|=”first”] All paragraphs whose att attribute value is a id attribute starts hyphen-separated list of with the word first in a words beginning with text hyphen-separated list of words elem[att^=”text”] All elem elements whose a[rel^=”prev”] All hypertext elements att attribute begins with whose rel attribute text [CSS3] begins with prev elem[att$=”text”] All elem elements whose a[href$=”org”] All hypertext elements att attribute ends with whose href attribute text [CSS3] ends with org elem[att*=”text”] All elem elements whose a[href*=”faq”] All hypertext elements att attribute contains the whose href attribute value text [CSS3] contains the text string faq Note that some of the attribute selectors listed in Figure 2-15 were first introduced in CSS3 and, thus, might not be supported in older browsers. Using Attribute Selectors REFERENCE To select an element based on its ID, use the elem#id or #id selector, where elem is the name of the element and id is the value of the id attribute. To select an element based on its class value, use the.class or the elem.class selectors, where class is the value of the class attribute. To select an element that contains an att attribute, use elem[att]. To select an element based on whether its attribute value equals a specified value, val, use elem[att="val"]. Tutorial 2 Getting Started with CSS | HTML and CSS HTML 113 In the Tri and Succeed Sports home page, the main content is enclosed within an article element with the ID about_tss. Alison wants the h1 and h2 heading styles you entered in the last session to be applied only to h1 and h2 elements within articles that have this particular ID. Revise the style sheet now. To apply an id selector: ◗ 1. Return to the tss_styles.css file in your editor. ◗ 2. Change the selectors for the h1 and h2 elements in the Heading Styles section to article#about_tss h1 and article#about_tss h2 respectively. Figure 2-16 highlights the revised selectors in the style sheet. Figure 2-16 Using an id selector selects h1 headings within an article element with the about_tss id selects h2 headings within an article element with the about_tss id ◗ 3. Save your changes to the file and then reload the tss_home.html file in your browser. Verify that the design of the h1 and h2 headings is only applied to the headings in the about_tss article but not to the other headings on the page. The article element will be used in other pages in the Tri and Succeed Sports website. Alison has provided you with three additional HTML files containing descriptions of the instruction her company offers for runners, cyclists, and swimmers. On those pages the article elements have the class attribute with the value syllabus. Create style rules for the h1 and h2 elements within the articles on those pages. To apply a class selector: ◗ 1. Use your editor to open the tss_run_txt.html, tss_bike_txt.html, and tss_swim_txt.html files from the html02 tutorial folder. Enter your name and the date in the comment section of each file and save them as tss_run.html, tss_bike.html, and tss_swim.html respectively. ◗ 2. Within each of the three files insert the following link elements before the closing tag to link these files to the tss_layout.css and tss_styles.css files, respectively: HTML 114 HTML and CSS | Tutorial 2 Getting Started with CSS ◗ 3. Take some time to study the content and structure of the files. Note that the article element has the class attribute with the value syllabus. Save your changes to the files. ◗ 4. Return to the tss_style.css file in your editor. ◗ 5. Within the Heading Styles section, add the following style rule to display the text of h1 and h2 headings in medium gray on a light purple background: article.syllabus h1, article.syllabus h2 { background-color: rgb(255, 185, 255); color: rgb(101, 101, 101); } Figure 2-17 highlights the new style rule in the file. Figure 2-17 Using a class selector selects h1 and h2 headings within article elements of the syllabus class displays the content in medium gray text on a light purple background ◗ 6. Save your changes to the style sheet and then open the tss_run.html file in your browser. Figure 2-18 shows the appearance of the h1 and h2 headings on this page. Figure 2-18 Headings on the running class page h1 heading text shows medium gray on a light purple background h2 heading text shows medium gray on a light purple background Tutorial 2 Getting Started with CSS | HTML and CSS HTML 115 ◗ 7. Use the navigation links on the page to view the content and design of the cycling and the swimming pages, and then confirm that the h1 and h2 headings on these pages have similar formats. INSIGHT Calculating Selector Specificity The general rule in CSS is that the more specific selector takes precedence over the more general selector, but the application of this rule is not always clear. For example, which of the following selectors is the more specific? header h1.top vs. #main h1 To answer that question, CSS assigns a numeric value to the specificity of the selector using the formula (inline, ids, classes, elements) where inline is 1 for an inline style and 0 otherwise, ids is 1 for every id in the selector, classes is 1 for every class or attribute in the selector, and elements is 1 for every element in the selector. For example, the selector ul#links li.first would have a value of (0, 1, 1, 2) because it references one id value (#links), 1 class value (.first) and two elements (ul and li). Specificity values are read from left to right with a larger number considered more specific than a smaller number. To answer our earlier question: the selector header h1.top has a value of (0, 0, 1, 2) but #main h1 has a value of (0, 1, 0, 1) and, thus, is considered more specific because 0101 is larger than 0012. By the way, every inline style has the value (1, 0, 0, 0) and thus will always be more specific than any style set in an embedded or external style sheet. Working with Fonts typography is the art of designing the appearance of characters and letters on a page. So far, the only typographic style you’ve used is the color property to set the text color. For the rest of this session, you’ll explore other properties in the CSS family of typographical styles, starting with choosing the text font. Choosing a Font Text characters are based on fonts that define the style and appearance of each character in the alphabet. The default font used by most browsers for displaying text is Times New Roman, but you can specify a different font for any page element using the following font-family property font-family: fonts; where fonts is a comma-separated list, also known as a font stack, of specific or generic font names. A specific font is a font that is identified by name, such as Times New Roman or Helvetica, and based on a font definition file that is stored on the user’s computer or accessible on the web. A generic font describes the general appearance of the characters in the text but does not specify any particular font definition file. Instead, HTML 116 HTML and CSS | Tutorial 2 Getting Started with CSS the font definition file is selected by the browser to match the general characteristics of the generic font. CSS supports the following generic font groups: serif—a typeface in which a small ornamentation appears at the tail end of each character sans-serif—a typeface without any serif ornamentation monospace—a typeface in which each character has the same width; often used to display programming code cursive—a typeface that mimics handwriting with highly stylized elements and flourishes; best used in small doses for decorative page elements fantasy—a highly ornamental typeface used for page decoration; should never be used as body text Because you have no control over which font definition file the browser will choose for a generic font, the common practice is to list specific fonts first, in order of preference, and end the font stack with a generic font. If the browser cannot find any of the specific fonts listed, it uses a generic font of its own choosing. For example, the style font-family: 'Arial Black', Gadget, sans-serif; tells a browser to use the Arial Black font if available; if not, to look for the Gadget font; and if neither of those fonts are available, to use its generic sans-serif font. Note that font names containing one or more blank spaces (such as Arial Black) must be enclosed within single or double quotes. Because the available fonts vary by operating system and device, the challenge is to choose a font stack limited to web safe fonts, which are fonts that will be displayed in mostly the same way in all operating systems and on all devices. Figure 2-19 lists several commonly used web safe font stacks. Figure 2-19 Web safe font stacks A general rule for printing is to use sans-serif fonts for headlines and serif fonts for Including too many fonts body text. For computer monitors, which have lower resolutions than printed material, can make your page the general rule is to use sans-serif fonts for headlines and body text, leaving serif fonts difficult to read. Don’t use for special effects and large text. more than two or three Currently, the body text for the Tri and Succeed Sports website is based on a serif typefaces within a single font applied by the browser. You’ll add the following font stack for sans-serif fonts, page. which will take precedence over the browser font style rule: font-family: Verdana, Geneva, sans-serif; Tutorial 2 Getting Started with CSS | HTML and CSS HTML 117 As a result of this style rule, the browser will first try to load the Verdana font, followed by the Geneva font. If both of these fonts are unavailable, the browser will load a generic sans-serif font of its own choosing. Add this font family to the style rule for the page body. To specify a font family for the page body: ◗ 1. Return to the tss_styles.css file in your editor. Font stacks should be listed ◗ 2. Add the following style to the style rule for the body element: in a comma-separated list font-family: Verdana, Geneva, sans-serif; with the most desired fonts listed first. Figure 2-20 highlights the new style for the body element. Figure 2-20 specifying a font stack browser attempts to use the Verdana font first, followed by Geneva, and finally any generic sans-serif font ◗ 3. Save your changes to the file and then reload the tss_home.html file in your browser. Figure 2-21 shows the revised appearance of the body text using the sans-serif font. Figure 2-21 sans-serif font applied to the home page © 2016 Cengage Learning; © Monkey Business Images/Shutterstock.com ◗ 4. View the other three pages in the website to verify that the sans-serif font is also applied to the body text on those pages. HTML 118 HTML and CSS | Tutorial 2 Getting Started with CSS Exploring Web Fonts Because web safe fonts limit your choices to a select number of fonts that have universal support, another approach is to supply a web font in which the definition font is supplied to the browser in an external file. Figure 2-22 describes the different web font file formats and their current levels of browser support. The format most universally accepted in almost all current browsers and on almost all devices is the Web Open Font Format (WOFF). Figure 2-22 Web font formats Format Description Browser Embedded A compact form of OpenType fonts IE OpenType (EOT) designed for use as embedded fonts in style sheets TrueType (TTF) Font standard used on the Mac OS IE, Firefox, Chrome, Safari, Opera and Microsoft Windows operating systems OpenType (O