The Basics of CSS3.pdf

Full Transcript

IN THIS CHAPTER »» Defining styles »» Formatting text »» Using the box model »» Sprucing up your tables...

IN THIS CHAPTER »» Defining styles »» Formatting text »» Using the box model »» Sprucing up your tables »» Positioning elements where you want them Chapter 2 The Basics of CSS3 I n the last chapter, I explain how to use HTML5 to display content on your web page. However, when you just use HTML5, things look pretty boring! This chapter shows you how to incorporate style into your web pages to help liven things up (even if you’re not an artist). First, I explain how to use CSS style sheets to style elements contained in the web page. Then I show you how to work with styles to change the color and font of text, make fancier lists, and spruce up your tables within your web pages. Finally, I explain how to work with the CSS positioning features to arrange your content in an appealing manner on the page. Understanding Styles When you specify an HTML5 element in your web page, the web browser decides just how that element should look. Browsers use a default styling to determine the difference between the text in an h1 element and the text in a blockquote element. Fortunately, another standard is available to work with HTML5 that helps you make your web pages unique. Back in Book 1, Chapter 1, I explain how Cascading Style Sheets (CSS) work to style HTML5 content on the web page. That’s the key to making your website stand out from the crowd! CHAPTER 2 The Basics of CSS3 103 The CSS standard specifies ways to define the color, size, and font type of text that appears on web pages. It also provides some styles for adding background colors and images and styling other types of elements on the web page. The CSS standard has evolved some over the years. At the time of this writing, it’s currently at version 3 — you’ll often see it referred to as CSS3, and that’s what I call it in this book. Now you’re ready to take a deeper dive into just how to use CSS3 in your web applications. This section walks through how CSS3 works and how you can use it to make your web pages look good. Defining the rules of CSS3 CSS3 uses rules to define how the browser should display content on the web page. Each rule consists of two parts: a selector that defines what elements the rule applies to and one or more declarations that define the style to apply. The format of the CSS3 rule looks like this: selector {declaration; declaration;...} In the rule definition, there are five ways to define the selector: »» Element type: The rule applies to all elements of the specified type. »» id attribute: The rule applies to the specific element with the specified id value. »» class attribute: The rule applies to all elements with the specified class value. »» Pseudo-element: The rule applies to a specific part within an element. »» Pseudo-class: The rule applies to elements in a specific state. Each declaration defines a CSS3 style property and its associated value. Each prop- erty sets a specific style (such as a color or a font) to the element the rule applies to. You must end each declaration with a semicolon, and you can list as many declarations as needed in the rule. Here’s the format of the property and its value as you list them in the declaration: property: value In the following sections, I explain in more detail the five ways to define a selector. 104 BOOK 2 HTML5 and CSS3 Element type You can apply the same styling to all elements of a specific type in your web page The Basics of CSS3 by specifying the element name as the selector: h1 {color: red;} This rule ensures that the browser displays all h1 elements in the web page using a red font color. If you want to apply the same styles to multiple types of elements, you can either list them as separate rules or group the elements together in the selector by sepa- rating the element names with commas, like this: h1, p {color: red;} This rule instructs the browser to style all h1 and p elements using a red font color. id attribute If you need to define a rule that applies to just a single element in the web page, use the id attribute as the selector. To specify an id attribute as the selector, place a pound sign (#) in front of the id name: #warning {color: red;} To use the rule in your HTML5 code, just apply the id attribute value to the ele- ment you need to style: This is a bad selection. The browser will apply that rule to the specific element that uses the id attribute value. class attribute If you need to define a rule that applies to multiple elements, but not necessarily all the elements of that type, use the class attribute as the selector. To specify a class attribute as the selector, place a period in front of the class name:.warning {color: red;} CHAPTER 2 The Basics of CSS3 105 Then just apply that class attribute to whichever elements you need to style using that rule: This is a bad selection. Please make another selection. As you can see from this example, you can apply the same class attribute value to different element types, making this a very versatile way of styling sections of your web page! If you decide you only need to apply a rule to one particular element type of the class, you can specify the element type in the selector before the class value: p.warning {color: red;} This rule will apply only to p elements with the class attribute value of warning. Pseudo-element The CSS standard defines a handful of special cases where you can apply styles to a subsection of the element content, and not the entire content of an element. These rules are called pseudo-elements. To use a pseudo-element rule, separate the rule from the selector it applies to using a double colon (::): selector::pseudo-element CSS3 supports a set of keywords for the pseudo-element names. For example, if you want to get fancy and style the first letter of a paragraph of text differently from the rest of the text, you can use the first-letter pseudo-element keyword: p::first-letter {font-size: 20px} The first-letter pseudo-element matches with only the first letter of the p ele- ment, as shown in Figure 2-1. CSS3 defines only a handful of pseudo-elements. Table 2-1 lists them. There aren’t a lot of pseudo-elements available, but these few pseudo-elements can come in handy for trying special formatting of your web pages. 106 BOOK 2 HTML5 and CSS3 The Basics of CSS3 FIGURE 2-1: Using the first-letter pseudo-element on text. TABLE 2-1 CSS3 Pseudo-Elements Pseudo-Element Description after Places an object before the selected element content before Places an object after the selected element content first-letter Applies the rule to the first letter of the selected element content first-line Applies the rule to the first line of the selected element content selection Applies the rule to the content area selected by the site visitor The after and before pseudo-elements may sound a bit strange, because there’s no content to style before or after an element. They’re most commonly used for placing images after or before the content in the element. Pseudo-class A pseudo-class applies the defined styles to an element that is in a specific state on the web page. The state refers to how the element behaves, such as buttons that are disabled, check boxes that are checked, or input boxes that have the browser focus. CHAPTER 2 The Basics of CSS3 107 These rules are commonly applied to hypertext links on the web page to help site visitors distinguish links they’ve already visited. You do that by using a series of four pseudo-class style rules: »» link: Applies the rule to a normal, unvisited link »» visited: Applies the rule to a link that the site visitor has already visited »» hover: Applies the rule when the site visitor hovers the mouse pointer over the link »» active: Applies the rule when the site visitor clicks the mouse on the link You specify pseudo-class rules using a single colon to separate it from the selector in the rule definition: a: link {color: orange;} a: visited {color: purple;} a: hover {color: green;} a: active {color: red;} All these pseudo-class rules apply to all the anchor elements in the web page and apply different colors to the hyperlink text depending on the hyperlink state. It’s extremely important to list the anchor element pseudo-class rules in the order shown here, or they won’t work! If you want to remove the underline that most browsers apply to hypertext links, add the following property to the pseudo-element style rule: text-decoration:none; There are lots of pseudo-classes that you can use to apply rules to specific ele- ments in the your web pages. Table 2-2 shows the list of available pseudo-classes in CSS3. Many of the pseudo-class style rules (such as first-child and last-child) work with the location of an element within the Document Object Model (DOM). Book 3, Chapter 2, discusses the DOM and how to use it to reference elements on the web page. 108 BOOK 2 HTML5 and CSS3 TABLE 2-2 The CSS3 Pseudo-Classes Pseudo-Class Description The Basics of CSS3 active The rule applies to hypertext links while the site visitor clicks them. checked The rule applies to input check boxes and radio options that are selected (checked). disabled The rule applies to input elements that are disabled. empty The rule applies to elements that have no children. enabled The rule applies to input elements that are enabled. first-child The rule applies to the first child element of a parent element. first-of-type The rule applies to the first child element of the same type as the parent. focus The rule applies to elements that have the browser focus. hover The rule applies to elements that the mouse pointer is hovering over. in-range The rule applies to elements whose value is within the specified range. invalid The rule applies to elements whose value is invalid. lang(language) The rule applies to elements with the lang attribute specified. last-child The rule applies to the last child element of a parent element. last-of-type The rule applies to the last child element of the same type as the parent. link The rule applies to unvisited hypertext link elements. not(selector) The rule applies to all elements except the specified selector elements. nth-child(n) The rule applies to the nth child of the parent element. nth-last-child(n) The rule applies to the nth child of the parent element counting backward from the last element. nth-of-type(n) The rule applies to the nth child element with the same type as the parent. only-of-type The rule applies to every element that is the only element of the same type as the parent. only-child The rule applies to every element that is the same only child of a parent. optional The rule applies to input elements that do not have the required attribute. out-of-range The rule applies to elements with a value out of the specified range. read-only The rule applies to elements with a readonly attribute specified. (continued) CHAPTER 2 The Basics of CSS3 109 TABLE 2-2 (continued) Pseudo-Class Description read-write The rule applies to elements without a readonly attribute specified. required The rule applies to elements with a required attribute specified. root The rule applies to the document’s root element. target The rule applies to the current active element specified. valid The rule applies to elements that have a valid value. visited The rule applies to hypertext links that the site visitor has already visited. Applying style rules In Book 1, Chapter 1, I discuss the different ways to apply CSS3 styles to an HTML5 document. To refresh your memory, there are three ways to do that: »» Inline styles: Place the style properties inside the HTML5 element opening tag, using the style attribute: Warning »» Internal styles: Use the tag to define a set of styles that apply to the entire document: h1 {color: red;} »» External styles: Use an external file to contain the style definitions, and then add the tag in the HTML5 document to reference the external style sheet: Note that with the inline style definitions, you leave off the selector part of the rule. Because the rule applies only to the element that declares it, there’s no need for the selector. With both the inline and external style sheet methods, you define the set of rules separately within the style sheet. The great benefit of using the external style sheet method is that you can then apply the same style sheet to all the pages of your website! 110 BOOK 2 HTML5 and CSS3 You can use any of these locations to define your style rules, or you can use them all at the same time! If two or more style rules apply to the same element on the The Basics of CSS3 web page, the cascading feature of CSS3 kicks in. CSS3 defines a specific process on how the browser applies conflicting rules to an element to ensure everything happens in order. The next section explains how that works. Cascading style rules As the name suggests, if you define multiple style rules for a web page, the rules cascade down from the lower-priority rules, which are applied first, to the higher- priority rules, which are applied later. Saying “down” from a lower to a higher priority may seem counterintuitive, but it’s common jargon in CSS circles. Just remember that the higher-priority rules take precedence over the lower-priority rules. The CSS3 standard defines a strict process for how browsers should apply style rules to each element. In Book 1, Chapter 1, I outline an abbreviated version of the cascading rules. There are actually ten different rule levels that the CSS3 standard defines for applying rules! However, most web designers don’t use all ten levels to define rules, so things don’t usually get that complicated. Table 2-3 shows the official CSS3 cascading rules process. TABLE 2-3 The CSS3 Cascading Rules Process Rule Type Description Priority Level Importance Rules contain the !important property and override all other rules 1 Inline Rules defined using the style attribute in an element opening tag 2 Media Rules defined for a specific media type 3 User defined Accessibility features defined in the browser by the site visitor 4 Specific selector A selector referring to an id, class, pseudo-element, or pseudo-class 5 Rule order When multiple rules apply to an element, the last rule declared wins 6 Inheritance Rules inherited from parent elements in the web page 7 Internal Rules defined in internal style sheets 8 External Rules defined in external style sheets 9 Browser default The default styles built into the browser, the lowest priority 10 CHAPTER 2 The Basics of CSS3 111 Notice that accessibility features have a special place in the cascading rule order. Many of your website visitors may have some type of viewing disability prevent- ing them from viewing your content as you style it. Most browsers allow users to define their own style features, such as specifying foreground and background contrasting colors or changing the font size to make text more readable. Now that you’ve seen how to define CSS3 rules and where to define them, the next step is to start learning some rules to apply to your web pages. The CSS3 standard defines a myriad of styles for you to use. Entire books have been written trying to cover all the different rules and features, such as CSS3 For Dummies by John Paul Mueller (Wiley). The remaining sections in this chapter walk you through some of the more commonly used rules that you’ll want to keep in mind as you design your dynamic web applications. Styling Text No place is styling more important than with the text that appears on your web page. You can transform a dull, boring website with just a few changes to the text styles. This section walks through the options you have available for styling text to help liven up your website. Setting the font A font defines how a medium displays the characters in the content. Whether it’s etching words into stone, setting text on paper using a printing press, or displaying pixels on a computer monitor, fonts help control how readers interpret the content. When you place text on your web page using HTML5, the browser selects a default font style, size, and format based on the element type, and it uses that same set- ting for all the text in those elements on your web page. That not only makes for a boring web page, but can also confuse your site visitors if all the content blends together. This section describes how you can change the font features the browser uses to display text in your web pages. Finding a family The CSS3 standard defines the font-family style property to allow you to change the style of font. Here’s the format for the font-family property: font-family: fontlist; 112 BOOK 2 HTML5 and CSS3 The fontlist value is a comma-separated list of font names. There are two ways to specify a font in the list: The Basics of CSS3 »» Using a specific font name: Specific font names require the browser to use that specific font to display the text, such as Times New Roman, Arial, or Helvetica. Browsers are limited to using only the fonts that are installed on the workstation, so specifying a specific font name can be a gamble. If that font isn’t available on the site visitor’s workstation, the browser will revert to the default font. It has become common practice to provide several options of font names in the font-family property. The browser will try to use the font presented first in the list, and if that’s not available, it’ll try the next font listed, and continue down the list. If no font is available, the browser reverts to the default font. »» Using a generic font group: Generic font groups give the browser a little more leeway in selecting a font to use. Instead of looking for a specific font, the browser can use any font that’s included in the font group. CSS3 defines the following font groups: cursive: A font that mimics handwritten text fantasy: An ornamental font used for special text monospace: A font that uses the same spacing for all characters sans-serif: A font without any ornamentation added to characters serif: A font that uses ornamentation at the tail of each character It’s common practice to list specific font names first in the font list and then, as a last resort, add a generic font group, like this: font-family: Arial, 'Times New Roman', sans-serif; With this rule, the browser will try to use the Arial font. If that’s not available on the visitor’s workstation, it will try to use the Times New Roman font. If Times New Roman is also not available, the browser will look for a font from the sans- serif font group. Note that for font names that contain spaces, you must enclose the name in single quotes. The CSS3 standard defines an exciting new feature called web fonts. Web fonts allow you to define your own font on a server so that browsers can download them along with the web page. I dive into using web fonts in more detail in Chapter 4 of this minibook. CHAPTER 2 The Basics of CSS3 113 Picking a size After selecting a font style to use, the next step is to decide what size the font should be. Browsers have built-in sizes for separating out the different header levels, as well as standard text. However, you can change that by using the font- size property: font-size: size; You’d think specifying a font size would be easy, but CSS3 actually allows you to specify the size in one of five different methods: »» As an absolute unit of measurement »» As a relative unit of measurement »» As a percentage of the space assigned to the element »» Using a size keyword »» Using a size keyword relative to the space assigned to the element You specify absolute units using a specific size value of measurement. To compli- cate things even more, CSS allows you to use six different units of measurements, shown in Table 2-4. TABLE 2-4 CSS Font-Size Absolute Units of Measurement Unit Description cm Centimeters in Inches mm Millimeters pc Picas pt Points px Pixels The first three units of measurement shown in Table 2-4 are easily recognizable, but the last three aren’t as common. There are 6 picas in an inch, and 72 points in an inch. The pixel unit originally matched up to pixels on a standard computer monitor, but with the advancement of monitor technology, that isn’t the case anymore. 114 BOOK 2 HTML5 and CSS3 You can specify the size using either a whole number or a decimal value: The Basics of CSS3 font-size: 0.25in; font-size: 48pt; The relative units of measurement set the size of the font relative to other elements on the web page. Table 2-5 shows the relative size units in CSS3. TABLE 2-5 CSS Font-Size Relative Units of Measurement Unit Description ch Relative to the size of the zero character em Relative to the size of the normal font size of the elements ex Relative to the normal height of the font size currently used rem Relative to the height of the root element vh Relative to 1% of the browser window height vw Relative to 1% of the browser window width vmax Relative to 1% of the larger of the browser window width or height vmin Relative to 1% of the smaller of the browser window width or height % As a percentage of the normal element size The em relative unit size is the most popular. It sizes the element relative to the text in the web page. For example, here’s a common rule that you’ll see: h1 {font-size: 2em;} This tells the browser to size the h1 element twice the size of the text in the web page. By using relative units, you can easily change the size of headings based on the size of the text in the content. If you decide to change the font size of the text in the web page, the headings will automatically change size to stay in the same proportion. To make things simpler, CSS also allows you to set the text size using a human- readable keyword. There are both absolute and relative keywords available: »» Absolute: xx-small, x-small, small, medium, large, x-large, xx-large »» Relative: smaller, larger CHAPTER 2 The Basics of CSS3 115 Using the keywords makes setting font sizes easier, but you’re still a little at the mercy of the browser. It’s up to the browser to determine just what is a small, medium, or large size font. Playing with color By default, browsers display all text in black on a white background. Things don’t get any more boring than that! One of the first steps in livening up your website is to change the text color scheme. There are two CSS3 properties that you need to do that: »» color: Selects the color the browser uses for the text font »» background-color: Selects the color the browser uses for the background You have a vast palette of colors to choose from for your color scheme. Usually, it’s a good idea to pick a color scheme for your website and try to stick with that for most of the web pages contained in the website. Often, a corporation will set the color scheme of its website based on the colors used in the company logo. Occasionally, you may need some content to pop out at visitors, so you’ll need to deviate some from the scheme. The original CSS standard provided three ways to define colors used in styles: »» With color names: You can choose a text value from a standard list of color names. CSS3 defines many different colors by name. If you plan on using a standard color, most likely you can call it just by its name: p {color: red; background-color: white;} »» With RGB hexadecimal values: If you want to fine-tune the colors your web page elements use, you can select the intensity of the red, green, and blue colors based on hexadecimal values from 00 to FF. If you’re into hexadecimal numbers, define the color as three hexadecimal values preceded by a pound sign: p {color: #ffa500;} The ffa500 value sets the red hue at full intensity, sets the green hue a little lower, and turns the blue hue off, producing the orange color. 116 BOOK 2 HTML5 and CSS3 »» With the rgb() function: You can select the color using decimal values from 0 to 255 for the red, green, and blue intensities. To specify the same color The Basics of CSS3 using the rgb() method, you’d use the following: p {color: rgb(255, 165, 0);} If you’re not picky about the shade of red you want, the first method will work just fine. But odds are, you’ll want to be more precise in your color selection (for example, matching the shade of red to the red in your company’s logo), so you’ll want to use one of the other two methods. Which of the other two methods you use is a matter of personal preference. The updated CSS3 standard provides four new ways of working with colors in your web pages: »» RGBA: Adds an opacity value to the standard RGB settings »» HSL: Defines the color as a hue, saturation, and lightness percentage »» HSLA: Defines the color as an HSL value, plus adds an opacity value »» Opacity: Defines a transparency value to make the element more opaque The main addition to the CSS3 color scheme is the opacity feature. The opacity fea- ture provides the ability to make elements transparent, or faded. The opacity value ranges from 0.0 (fully transparent) to 1.0 (no transparency, also called opaque). Here’s an example to demonstrate just how changing colors in elements works: 1. Open your favorite text editor, program editor, or integrated develop- ment environment (IDE) package. 2. Enter the following code into the editor window: Testing colors in CSS3 p { font-family: Arial, Helvetica, sans-serif; color: #ff0000; background-color: cyan; } CHAPTER 2 The Basics of CSS3 117 h1 { color: rgb(255, 165, 0); background-color: green; } Testing the color scheme The quick brown fox jumps over the lazy dog. This is the end of the color test 3. Save the program as colortest.html in the DocumentRoot folder of your web server. If you’re using XAMPP, it’s c:\xampp\htdocs for Windows or /Applications/ XAMPP/htdocs for macOS. 4. Start the web server. If you’re using XAMPP, launch the XAMPP Control Panel and then click the Start button for the Apache web server. 5. Open your browser and go to the URL for the new file: http://localhost:8080/colortest.html Note: You may need to change the port in the URL to what your web server uses. 6. Stop the web server and close the browser. You should see in the output from your web page that the browser uses different colors for the h1 elements and the p elements. However, notice that there’s some whitespace between the elements, as shown in Figure 2-2. You didn’t define any space between the p and h1 elements in the HTML5 code, so why is that there? You may be thinking that something has gone wrong with the browser, but actually, it’s a feature of CSS that I cover next. 118 BOOK 2 HTML5 and CSS3 The Basics of CSS3 FIGURE 2-2: Displaying elements with different colors in CSS3 Working with the Box Model CSS3 handles all elements on the web page using the box model, which defines the area inside and around the element and provides a way for you to alter the style of those features. Figure 2-3 shows the box model defined in CSS3. FIGURE 2-3: The CSS3 box model. The box model defines four different sections in the element. Working from the inside out, they are as follows: »» Content: The text or image the element contains »» Padding: The space around the content CHAPTER 2 The Basics of CSS3 119 »» Border: An area, usually visible, that goes around the content and padding »» Margin: The space outside of the element border, between elements With CSS3, you can alter the padding, margin, and border around an element to help make it stand out in the web page. You do that using the padding, margin, and border style properties. Let’s correct the colortest.html code to remove the margin around the elements and add some extra padding to see how that changes things: 1. Open the colortest.html file you created in the “Playing with color” section in your favorite text editor, program editor, or IDE package. 2. Modify the p and h1 element styles to set the element margins to 0px and add 10px of padding. The styles should now look like this: p { font-family: Arial, Helvetica, sans-serif; color: #ff0000; background-color: cyan; margin: 0px; padding: 10px; } h1 { color: rgb(255, 165, 0); background-color: green; margin: 0px; padding: 10px; } 3. Save the updated colortest.html file. 4. Start the web server. If you’re using XAMPP, launch the XAMPP Control Panel and then click the Start button for the Apache web server. 5. Open your browser and go to the URL for the new file: http://localhost:8080/colortest.html 120 BOOK 2 HTML5 and CSS3 Note: You may need to change the port in the URL to what your web server uses. The Basics of CSS3 6. Stop the web server and close the browser. Figure 2-4 shows the web page this code produces. FIGURE 2-4: The updated colortest.html file output. Notice that the white space is gone and the background space around the text in the headings and paragraph is larger. Feel free to play around with the margin and padding numbers in the HTML5 code and watch how it changes the display results. Styling Tables The previous chapter explains how to create tables using HTML5. Older versions of HTML defined attributes in the table element to help add some features, such as creating borders around the table cells and sizing the table cells. However, HTML5 removed all those attributes, so it’s up to CSS to provide those features. CHAPTER 2 The Basics of CSS3 121 Table borders When you’re presenting data in tables, you may want to create borders around the table and around the individual cells in the table. You do that with the CSS border property: table {border: 1px solid black;} The first value in the border property (1px) is the width of the border. The second value (solid) is the type of border; you can specify dashed, dotted, double, or solid for the border type. The third value (black) specifies the color of the border. You can add borders around any of the table family of elements — table, th, tr, or td. However, if you specify the border property for all of them, you’ll see dou- ble borders around the individual cells. To prevent that from happening, add the border-collapse property to the rule, and set its value to collapse. If you only want to show horizontal lines between the table rows, you can use the border-bottom property for the tr element. This only creates borders at the bot- tom of each row. Follow these steps to add borders around a table: 1. Open the mytable.html file that you created in the preceding chapter in your favorite text editor, program editor, or IDE package. If you haven’t yet read Chapter 1 of this minibook, you’ll have to turn back and at least work through the section on tables before proceeding with these steps. I’ll wait for you! 2. Add a style element to the head section of the document to define the table styling rule: table tr td { border: 1px solid black; border-collapse: collapse; } I included the border-collapse property to prevent double borders from appearing. 3. Save the file. 122 BOOK 2 HTML5 and CSS3 4. Start your web server software, open your browser, and go to the following URL: The Basics of CSS3 http://localhost:8080/mytable.html 5. Close the browser and stop your web server software. With the added stylings, you should see a single border line around each table cell and a single border line around the entire table, as shown in Figure 2-5. FIGURE 2-5: Adding a border to the table. Now that you have borders around each cell, it may seem a bit more obvious how cramped the data inside the table looks. You can do some more playing around with sizing and positioning the text inside each cell. I cover that in the next section. Table data As you can see in Figure 2-5, by default, the browser creates the table cells just large enough to contain the largest data value in the cells. That can make for a somewhat cramped table. Fortunately, you can add a little more space around the data in the table cells using some additional CSS properties. CHAPTER 2 The Basics of CSS3 123 Padding the cells A padded cell sounds somewhat ominous, but adding the padding property to your table cells can make a huge difference in the appearance of the table data: table tr td { border: 1px solid black; border-collapse: collapse; padding: 10px; } When you provide some additional space inside the table cells, you have some more options on where the data appears within the table. Aligning text in the cells You can align the data to the left side, center, or right side of the cell with the text-align property: table th { border: 1px solid black; border-collapse: collapse; padding: 10px; text-align: center; } This definition centers the text in the table header (th) elements. If you also want to move the text upward inside the cell, use the vertical-align property. Coloring tables Just using the default black-and-white tables can quickly put your site visitors to sleep! Add the color and background-color properties to your table to make it stand out. You can apply the colors to the entire table, individual rows, or even individual cells. To simulate the old mainframe printer report style using alternating row colors in the table, use the nth-child pseudo-class to style every other row in the table as a different color, like this: tr: nth-child(even) { background-color: lightgreen; } If you’re old enough to remember the mainframe computer report days, this should bring back memories! 124 BOOK 2 HTML5 and CSS3 Another feature that comes in handy is to use the hover pseudo-class to change the background color of an individual cell as your site visitor hovers the mouse The Basics of CSS3 pointer over it: td: hover { background-color: yellow; } Now things are really starting to get fancy! Positioning Elements By default, browsers place elements in the window following a set order. As the web page defines each element, the browser places it in the window starting at the upper-left corner of the window, proceeding from left to right, and top to bottom. To demonstrate this, let’s run a quick test. You’ll create a web page that contains five sections: »» A header to display at the top of the web page »» A footer to display at the bottom of the web page »» A navigation section to display on the left side of the middle section »» An aside section to display on the right side of the middle section »» A main content section to display in the middle of the middle section This is a pretty standard web page layout structure, which I’m sure you’ve seen lots of times as you’ve browsed the web. Follow these steps to run the test: 1. Open your favorite text editor, program editor, or IDE package, and enter the following code: Positioning Test CHAPTER 2 The Basics of CSS3 125 header { background-color: red; margin: 0px; padding: 10px; height: 25px; width: 600px; } nav { background-color: blue; margin: 0px; padding: 10px; height: 125px; width: 200px; } section { background-color: green; margin: 0px; padding: 10px; height: 125px; width: 200px; } aside { background-color: yellow; margin: 0px; padding: 10px; height: 125px; width: 200px; } footer { background-color: orange; margin: 0px; padding: 10px; height: 25px; width: 600px; } This is the header Navigation 126 BOOK 2 HTML5 and CSS3 Section Aside The Basics of CSS3 This is the footer 2. Save the file as positiontest.html in the DocumentRoot folder of your web server. 3. Start the web server, open your browser, and go to the following URL: http://localhost:8080/positiontest.html 4. Close the browser and stop the web server. This test creates a web page that contains a header section, a navigation section, a main content section, an aside section, and a footer section. It uses the height and width style properties to define how large each section should be and sets a different background color for each section so you can tell them apart on the web page. However, when you display the web page, you’ll probably be a bit disap- pointed with the results, which are shown in Figure 2-6. The browser positioned each of the different sections in the order you defined them, each on top of the other. Ouch! That’s not what we wanted at all! FIGURE 2-6: Displaying the web page with no positioning. CHAPTER 2 The Basics of CSS3 127 To get the browser to place the different web page sections the way we want, we’ll need to use some of the positioning properties available in CSS. The next sections walk you through how to do that. Putting elements in a specific place Placing elements in specific locations on the web page requires using the position- ing properties available in CSS. There are three main positioning properties that are normally used: »» position: Sets the position method the browser should use to place the element »» top: Defines the location for the top of the element »» left: Defines the location for the left side of the element The position property defines what method the browser uses to place the ele- ment in the web page. There are four different positioning methods: »» absolute: Changes the element’s position relative to the nearest positioned element that precedes it. »» fixed: Places the element in a fixed location in the browser window. If the site visitor scrolls the window, the element stays in the same spot. »» relative: Changes the element’s position relative to the default position. »» static: Places the element in its normal location in the web page following the default placement rules. To use the absolute, fixed, and relative positioning methods, you need to define the location in the browser window where the element will be placed. You do that using the top and left properties. Let’s change the positiontest.html test file to use absolute positioning to place the sections. Just follow these steps: 1. Open the positiontest.html file in your favorite text editor, program editor, or IDE package. 128 BOOK 2 HTML5 and CSS3 2. Modify the styles defined so they look like this: The Basics of CSS3 header { background-color: red; margin: 0px; padding: 10px; height: 25px; width: 600px; position: absolute; top: 0px; left: 0px; } nav { background-color: blue; margin: 0px; padding: 10px; height: 125px; width: 200px; position: absolute; top: 46px; left: 0px; } section { background-color: green; margin: 0px; padding: 10px; height: 125px; width: 200px; position: absolute; top: 46px; left: 201px; } aside { background-color: yellow; margin: 0px; padding: 10px; height: 125px; width: 200px; CHAPTER 2 The Basics of CSS3 129 position: absolute; top: 46px; left: 402px; } footer { background-color: orange; margin: 0px; padding: 10px; height: 25px; width: 600px; position: absolute; top: 192px; left: 0px; } 3. Save the updated positiontest.html file as positiontest2.html. 4. Start your web server, open a browser, and go to the following URL: http://localhost:8080/positiontest2.html 5. Close the browser and stop the web server. The additional code sets the positioning method for the browser to use for each section to absolute, which means it will place the sections at exactly the place in the browser window you define using the top and left properties. When you display the web page, you should see the result as shown in Figure 2-7. Now things are starting to look like a real web page! Floating elements Absolute positioning has made a huge difference in how we can lay out elements in our web pages, but it doesn’t solve all problems. You’ve probably already real- ized that trying to figure out the exact location for each element in a compli- cated web page would be somewhat difficult. Also, you’ll notice as you resize the browser window that the sections stay in a fixed location and size — they don’t expand or shrink with the browser window. Fortunately, there’s a way you can avoid these problems. 130 BOOK 2 HTML5 and CSS3 The Basics of CSS3 FIGURE 2-7: Using absolute positioning to place sections in the web page. CSS uses a feature called the float property to aid in positioning elements in the web page using a more dynamic method. The float property allows you to take an element out of the normal positioning flow in the web page and position it within the right or left edge of its parent container element. You don’t need to calculate the exact position for the elements within the parent. The format of the float property is pretty simple: float: position The position value can be none, left, or right. The float property is most often used to create columns in a web page layout. Instead of using absolute positioning for the columns, you define a parent con- tainer element, and then just float the column elements inside the parent. Let’s give that a try with our positiontest.html example. You’ll add a div ­ lement to use as the container for the middle three sections (nav, section, and e aside) in the web page document. Follow these steps: 1. Open the original positiontest.html file in your favorite text editor, program editor, or IDE package. CHAPTER 2 The Basics of CSS3 131 2. Modify the styles defined so they look like this: header { background-color: red; margin: 0px; padding: 10px; height: 25px; width: 100% } nav { background-color: blue; margin: 0px; padding: 10px; height: 125px; width: 20%; float: left; } section { background-color: green; margin: 0px; padding: 10px; height: 125px; width: 55%; float: left; } aside { background-color: yellow; margin: 0px; padding: 10px; height: 125px; width: 20%; float: right; } footer { clear: both; background-color: orange; margin: 0px; padding: 10px; 132 BOOK 2 HTML5 and CSS3 height: 25px; width: 100%; The Basics of CSS3 } 3. Modify the HTML code to add a div parent element around the nav, section, and aside elements. That code should look like this: This is the header Navigation Section Aside This is the footer 4. Save the updated positiontest.html file as positiontest3.html. 5. Start your web server, open your browser, and go to the following URL: http://localhost:8080/positiontest2.html 6. Close the browser and stop the web server. When you view the resulting web page, it should look similar to Figure 2-8. FIGURE 2-8: Using float positioning to place sections in the web page. CHAPTER 2 The Basics of CSS3 133 The float property in the nav, section, and aside elements causes them to float within the parent div element. I gave the parent element an id attribute value of container to help me remember its purpose. It’s not necessary for it to have an id attribute defined because it isn’t styled by itself. Each of the inner sections appears side by side, as long as there’s enough space for them in the browser window. By using a percentage value for the width, this creates what’s called a liquid layout. With a liquid layout, if you resize the browser window, the individual section elements resize as well. If you resize the browser window too small, the browser automatically repositions the elements so that they all appear in the window. 134 BOOK 2 HTML5 and CSS3

Use Quizgecko on...
Browser
Browser