Essential CSS - Appendixes - HTML5: The Missing Manual Matthew MacDonald (2013)

HTML5: The Missing Manual Matthew MacDonald (2013)

Part 4. Appendixes

Appendix A

Appendix B

Appendix A. Essential CSS

It’s no exaggeration to say that modern web design wouldn’t be possible without CSS, the Cascading Style Sheet standard. CSS allows even the most richly formatted, graphically complex web pages to outsource the formatting work to a separate document—a style sheet. This keeps the web page markup clean, clear, and readable.

To get the most out of HTML5 (and this book), you need to be familiar with the CSS standard. If you’re a CSS pro, don’t worry about this appendix—carry on with the material in the rest of the book, and pay special attention to Chapters Chapter 6 and Chapter 7, which introduce many of the new style features that CSS3 adds. But if your CSS skills are a bit rusty, this appendix will help to refresh your memory before you go any further.

NOTE

This appendix gives a very quick (and not comprehensive) rundown of CSS. If you’re still overwhelmed, consult a book that deals with CSS in more detail, like CSS3: The Missing Manual by David Sawyer McFarland.

Adding Styles to a Web Page

There are three ways to use styles in a web page.

The first approach is to embed style information directly into an element using the style attribute. Here’s an example that changes the color of a heading:

<h1 style="color: green">Inline Styles are Sloppy Styles</h1>

This is convenient, but it clutters the markup terribly. You have to style every line, one by one.

The second approach is to embed an entire style sheet in a <style> element, which you must place in the page’s <head> section:

<head>

<title>Embedded Style Sheet Test</title>

<style>

...

</style>

</head>

This code separates the formatting from your web page markup but still keeps everything together in one file. This approach makes sense for one-off formatting tasks (when you don’t want to reuse your formatting choices in another page), and it’s a good choice for simple tests and examples, like the ones included with this book. However, it’s not so great for a real-world, professional website, because it leads to long, bloated pages.

The third approach is to link to a separate style sheet file by adding a <link> element to the <head> section. Here’s an example that tells a web browser to apply the styles from the style sheet named SampleStyles.css:

<head>

<title>External Style Sheet Test</title>

<link rel="stylesheet" href="SampleStyles.css">

</head>

This approach is the most common and the most powerful. It gives you the flexibility to reuse your styles in other pages. If you want, you can further divide your styles into multiple style sheets and link to as many as you need in any HTML page.

NOTE

A simple philosophy underpins modern web development. HTML markup is for structuring a page into logical sections (paragraphs, headings, lists, images, links, and so on), while a CSS style sheet is for formatting it (by specifying fonts, colors, borders, backgrounds, and layout). Follow this rule, and your web pages will be easy to edit. You’ll also be able to change the formatting and layout of your entire website simply by modifying its linked style sheet. (To see a truly impressive example of style sheet magic, check out www.csszengarden.com, where one website is given more than 200 different faces, simply by swapping in different style sheets.)

The Anatomy of a Style Sheet

A style sheet is a text file, which you’ll usually place on a web server alongside your HTML pages. It contains one or more rules. The order of these rules doesn’t matter.

Each rule applies one or more formatting details to one or more HTML elements. Here’s the structure of a simple rule:

selector {

property: value;

property: value;

}

And here’s what each part means:

§ The selector identifies the type of content you want to format. A browser hunts down all the elements in the web page that match your selector. There are many different ways to write a selector, but one of the simplest approaches (shown next) is to identify the elements you want to format by their element names. For example, you could write a selector that picks out all the level-one headings in your page.

§ The property identifies the type of formatting you want to apply. Here’s where you choose whether you want to change colors, fonts, alignment, or something else. You can have as many property settings as you want in a rule—this example has two.

§ The value sets a value for the property. For example, if your property is color, the value could be light blue or a queasy green.

Now here’s a real rule that does something:

h1 {

text-align: center;

color: green;

}

Pop this text into a style sheet and save it (for example, as SampleStyles.css). Then, take a sample web page (one that has at least one <h1> heading) and add a <link> element that refers to this style sheet. Finally, open this page in a browser. You’ll see that the <h1> headings don’t have their normal formatting—instead, they will be centered and green.

CSS Properties

The previous example introduces two formatting properties: text-align (which sets how text is positioned, horizontally) and color (which sets the text color).

There are many, many more formatting properties for you to play with. Table A-1 lists some of the most commonly used. In fact, this table lists almost all the style properties you’ll encounter in the examples in this book (not including the newer CSS3 properties that are described in ChaptersChapter 6 and Chapter 7).

Table A-1. Commonly used style sheet properties, by category

PROPERTIES

Colors

color

background-color

Spacing

margin

padding

margin-left, margin-right, margin-top, margin-bottom

padding-left, padding-right, padding-top, padding-bottom

Borders

border-width

border-style

border-color

border (to set the width, style, and color in one step)

Text alignment

text-align

text-indent

word-spacing

letter-spacing

line-height

white-space

Fonts

font-family

font-size

font-weight

font-style

font-variant

text-decoration

@font-face (for using fancy web fonts; see Web Fonts)

Size

width

height

Layout

position

left, right

float, clear

Graphics

background-image

background-repeat

background-position

TIP

If you don’t have a style sheet book on hand, you can get an at-a-glance overview of all the properties listed here (and more) at www.htmldog.com/reference/cssproperties. You can also get more information about each property, including a brief description of what it does and the values it allows.

Formatting the Right Elements with Classes

The previous style sheet rule formatted all the <h1> headings in a document. But in more complex documents, you need to pick out specific elements and give them distinct formatting.

To do this, you need to give these elements a name with the class attribute. Here’s an example that creates a class named ArticleTitle:

<h1 class="ArticleTitle">HTML5 is Winning</h1>

Now you can write a style sheet rule that formats only this heading. The trick is to write a selector that starts with a period, followed by the class name, like this:

.ArticleTitle {

font-family: Garamond, serif;

font-size: 40px;

}

Now, the <h1> that represents the article title is sized up to be 40 pixels tall.

You can use the class attribute on as many elements as you want. In fact, that’s the idea. A typical style sheet is filled with class rules, which take web page markup and neatly carve it into stylable units.

Finally, it’s worth noting that you can create a selector that uses an element type and a class name, like this:

h1.ArticleTitle {

font-size: 40px;

}

This selector matches any <h1> element that uses the ArticleTitle class. Sometimes, you may write this sort of style rule just to be clear. For example, you may decide to write your rule this way to make it clear that the ArticleTitle applies only to <h1> headings and shouldn’t be used anywhere else. But most of the time, web designers just create straight classes with no element restrictions.

NOTE

Different selectors can overlap. If more than one selector applies to the same element, they will both take effect, with the most general being applied first. For example, if you have a rule that applies to all headings and a rule that applies to the class named ArticleTitle, the all-headings rule is applied first, followed by the class rule. As a result, the class rule can override the properties that are set in the all-headings rule. If two rules are equally specific, the one that’s defined last in the style sheet wins.

Style Sheet Comments

In a complicated style sheet, it’s sometimes worth leaving little notes to remind yourself (or to let other people know) why a style sheet rule exists and what it’s designed to do. Like HTML, CSS lets you add comments, which the web browser ignores. However, CSS comments don’t look like HTML comments. They always start with the characters /* and end with the characters */. Here’s an example of a somewhat pointless comment:

/* The heading of the main article on a page. */

.ArticleTitle {

font-size: 40px;

}

Slightly More Advanced Style Sheets

You’ll see an example of a practical style sheet in a moment. But first you need to consider a few of the finer points of style-sheet writing.

Structuring a Page with <div> Elements

When working with style sheets, you’ll often use the <div> element to wrap up a section of content:

<div>

<p>Here are two paragraphs of content.</p>

<p>In a div container.</p>

</div>

On its own, the <div> does nothing. But it gives you a convenient place to apply some class-based style sheet formatting. Here are some examples:

§ Inherited values. Some CSS properties are inherited, which means the value you set in one element is automatically applied to all the elements inside. One example is the set of font properties—set them on a <div>, and everything inside gets the same text formatting (unless you override it in places with more specific formatting rules).

§ Boxes. A <div> is a natural container. Add a border, some spacing, and a different background color (or image), and you have a way to make select content stand out.

§ Columns. Professional websites often carve their content up into two or three columns. One way to make this happen is to wrap the content for each column in a <div>, and then use CSS positioning properties to put them in their proper places.

TIP

Now that HTML5 has introduced a new set of semantic elements, the <div> element doesn’t play quite as central a role. If you can replace a <div> with another, more meaningful semantic element (like <header> or <figure>), you should do that. But when nothing else fits, the <div> remains the go-to tool. Chapter 2 has a detailed description of all the semantic elements.

The <div> element also has a smaller brother named <span>. Like the <div> element, the <span> element has no built-in formatting. The difference is that <div> is a block element, designed to wrap separate paragraphs or entire sections of content, while <span> is an inline element that’s meant to wrap smaller portions of content inside a block element. For example, you can use <span> to apply custom formatting to a few words inside a paragraph.

NOTE

CSS encourages good design. How? If you want to use CSS effectively, you need to properly plan your web page’s structure. Thus, the need for CSS encourages even casual web-page writers to think seriously about how their content is organized.

Multiple Selectors

Sometimes, you might want to define some formatting that applies to more than one element or more than one class. The trick is to separate each selector with a comma.

For example, consider these two heading levels, which have different sizes but share the same title font:

h1 {

font-family: Impact, Charcoal, sans-serif;

font-size: 40px;

}

h2 {

font-family: Impact, Charcoal, sans-serif;

font-size: 20px;

}

You could pull the font-family setting into a separate rule that applies to both heading levels, like this:

h1, h2 {

font-family: Impact, Charcoal, sans-serif;

}

h1 {

font-size: 40px;

}

h2 {

font-size: 20px;

}

It’s important to understand that this isn’t necessarily a better design. Often, it’s better to duplicate settings because that gives you the most flexibility to change formatting later on. If you have too many shared properties, it’s more awkward to modify one element type or class without affecting another.

Contextual Selectors

A contextual selector matches an element inside another element. Here’s an example:

.Content h2 {

color: #24486C;

font-size: medium;

}

This selector looks for an element that uses the Content class. Then it looks for <h2> elements inside that element and formats them with a different text color and font size. Here’s an example of an element it will format:

<div class="Content">

...

<h2>Mayan Doomsday</h2>

...

</div>

In the first example, the first selector is a class selector, and the second selector (the contextual one) is an element type selector. However, you can change this up any way you want. Here’s an example:

.Content .LeadIn {

font-variant: small-caps;

}

This selector looks for an element in the LeadIn class, wrapped inside an element in the Content class. It matches this element:

<div class="Content">

<p><span class="LeadIn">Right now</span>, you're probabl

y feeling pretty

good. After all, life in the developed world is comfortable ...</p>

...

</div>

Once you get the hang of contextual selectors, you’ll find that they’re quite straightforward and ridiculously useful.

ID Selectors

Class selectors have a closely related cousin called ID selectors. Like a class selector, the ID selector lets you format just the elements you choose. And like a class selector, the ID selector lets you pick a descriptive name. But instead of using a period, you use a number-sign character (#):

#Menu {

border-width: 2px;

border-style: solid;

}

As with class rules, browsers don’t apply ID rules unless you specifically tell them to in your HTML. However, instead of switching on the rules with a class attribute, you do so with the id attribute. For example, here’s a <div> element that uses the Menu style:

<div id="Menu">...</div>

At this point, you’re probably wondering why you would use an ID selector—after all, the ID selector seems almost exactly the same as a class selector. But there’s one difference: You can assign a given ID to just one element in a page. In the current example, that means only one <div> can be labeled as a Menu. This restriction doesn’t apply to class names, which you can reuse as many times as you like.

That means the ID selector is a good choice if you want to format a single, never-repeated element on your page. The advantage is that the ID selector clearly indicates the special importance of that element. For example, if a page has an ID selector named Menu or NavigationBar, the web designer knows there’s only one menu or navigation bar on that page. Of course, you never need to use an ID selector. Some web designers use class selectors for everything, whether the section is unique or not. It’s a matter of personal preference.

NOTE

The id attribute also plays an important role in JavaScript, letting web page designers identify a specific element so it can be manipulated in code. The examples in this book use ID rules whenever an element already uses the id attribute for JavaScript, which avoids setting both the id attribute and the class attribute. In every other case, the examples use class rules, regardless of whether or not the element is unique.

Pseudo-Class Selectors

So far, the selectors you’ve seen have been straightforward. They’ve taken a single, obvious piece of information into consideration, like the element type, class name, or ID name. Pseudo-classes are a bit more sophisticated. They take extra information into account—information that might not be set in the markup or might be based on user actions.

For most of CSS history, browsers have supported just a few pseudo-classes, which were mostly designed for formatting links. The :link pseudo-class formats any link that points to a new, unvisited location. The :visited pseudo-class applies to any link that points to a location the reader has already visited. The :hover pseudo-class formats a link when a visitor moves the mouse over it, and the :active pseudo-class formats a link as a reader clicks it, before releasing the mouse button. As you can see, pseudo-classes always start with a colon (:).

Here’s a style rule that uses pseudo-classes to create a misleading page—one where visited links are blue and unvisited links are red:

a:link {

color: red;

}

a:visited {

color: blue;

}

You can also use pseudo-classes with a class name:

.BackwardLink:link {

color: red;

}

.BackwardLink:visited {

color: blue;

}

Now an anchor element needs to specify the class name to display your new style, as shown here:

<a class="BackwardLink" href="...">...</a>

Pseudo-classes aren’t just a way to format links. The :hover pseudo-class is useful for applying animated effects and creating fancy buttons. It’s used with CSS3 transitions, as explained in Chapter 6 (Creating Effects with Transitions).

NOTE

CSS3 also introduces some more advanced pseudo-classes that take other details into consideration, like the position of an element relative to other elements or the state of an input control in a web form. These pseudo-classes aren’t described in this book, but you can learn about them from a Smashing Magazine article at http://tinyurl.com/pc-css3.

Attribute Selectors

Attribute selection is a feature offered by CSS3 that lets you format a specific type of element that also has a specific value set for one of its attributes. For example, consider the following style rule, which applies only to text boxes:

input[type="text"] {

background-color:silver;

}

First, this selector grabs all the <input> elements. Then, it filters down its selection to include just those <input> elements that have a type attribute set to “text”, which it then formats. In the following markup, that means the first <input> element gets the silver background but the second doesn’t:

<label for="name">Name:</label><input id="name" type="text"><br>

<input type="submit" value="OK">

Technically, you don’t need to include the type=“text” attribute in the first <input> element, because that’s the default value. If you leave it out, the attribute selector still works, because it pays attention to the current value of the attribute and doesn’t care how that value is defined in your markup.

Similarly, you could create a rule that formats the caption for this text box but ignores all other labels:

label[for="name"] {

width: 200px;

}

NOTE

You can still get a bit fancier with attribute selectors. For example, you can match a combination of attribute values, or match part of an attribute value. These techniques are awfully clever but inject too much complexity into the average style sheet. To get the lowdown, see the CSS3 standard for selectors at http://tinyurl.com/s-css3.

A Style Sheet Tour

Chapter 2 shows how you can learn to use HTML5’s semantic elements by revising a straightforward, but nicely formatted page called ApocalypsePage_Original.html (Figure A-1). This page links to a style sheet named ApocalypsePage_Original.css:

<!DOCTYPE html>

<html lang="en">

<head>

<title>Apocalypse Now</title>

<link rel="stylesheet" href="ApocalypsePage_Original.css">

</head>

...

The style sheet is straightforward and relatively brief, weighing in somewhere over 50 lines. In this section, you’ll dissect each one of its style rules.

The styles in this page are simple, but they follow the basic organizational principles that you’ll see put into practice throughout this book.

Figure A-1. The styles in this page are simple, but they follow the basic organizational principles that you’ll see put into practice throughout this book.

First, the style sheet begins with a selector that targets the <body> element, which is the root of the entire web page. This is the best place to set inherited values that you want to apply, by default, to the rest of the document. Examples include margins, padding, background color, the font, and the width:

body {

font-family: "Lucida Sans Unicode", "Lucida Grande", Geneva, sans-serif;

max-width: 800px;

}

When setting the font-family property in CSS, you should follow two rules. First, use a web-safe font—one of the small number of fonts that are known to work on virtually all web-connected computers (see http://tinyurl.com/ws-fonts for a list). Second, use a font list that starts with the specific variant you want, followed by other possible fallbacks, and ends with serif or sans-serif (two font instructions that all browsers understand). If you prefer to use a fancy font that the user must download from your web server, check out the CSS3 web font feature on Web Fonts.

The body rule also sets a maximum width, capping it at 800 pixels. This rule prevents overly long, unreadable lines when the browser window is made very wide. There are other possible techniques for handling this situation, including splitting the text into columns (Putting Text in Multiple Columns), using CSS media queries (Adapting Your Layout with Media Queries), or creating a sidebar to soak up the additional space. However, although setting a fixed 800-pixel width isn’t the most glamorous solution, it’s a common approach.

Next in the style sheet is a class-specific rule that formats the header region at the top of the page:

.Header {

background-color: #7695FE;

border: thin #336699 solid;

padding: 10px;

margin: 10px;

text-align: center;

}

NOTE

In this example, the header is simply a <div> with the class name Header. However, Chapter 2 explains how you might consider replacing that with HTML5’s <header> element.

There’s a lot of information packed into this rule. The background-color property can be set, like all CSS colors, using a color name (which provides relatively few choices), an HTML color code (as done here), or the rgb() function (which specifies the red, green, and blue components of the color). The examples in this book use all three approaches, with color names in simple examples and color codes and the rgb() function in more realistic examples.

Incidentally, every HTML color code can be written with the rgb() function, and vice versa. For example, you can write the color in the above example using the rgb() function, like this:

background-color: rgb(118,149,254);

TIP

To actually get the RGB values for the color you want, try an online color picker, or look the numbers up in your favorite drawing or graphics program.

The header rule also draws a thin border around its edges. It uses the all-in-one border property to specify the border thickness, border color, and border style (for example, solid, dashed, dotted, double, groove, ridge, inset, or outset) in one property setting.

With the background color and border details out of the way, the header rule sets 10 pixels of padding (between the content inside and the border) and 10 pixels of margin space (between the border and the surrounding web page). Finally, the text inside the header is centered.

The following three rules use contextual selectors to control how elements are formatted inside the header. The first one formats <h1> elements in the header:

.Header h1 {

margin: 0px;

color: white;

font-size: xx-large;

}

TIP

When setting a font size, you can use keywords (like the xx-large value used here). Or, if you want precise control, you can supply an exact measurement using pixels or em units.

The next two rules format two classes, named Teaser and Byline, which are also inside the header:

.Header .Teaser {

margin: 0px;

font-weight: bold;

}

.Header .Byline {

font-style: italic;

font-size: small;

margin: 0px;

}

This code works because the header contains two <span> elements. One <span> has the class name Teaser, and contains the subtitle. The second <span> has the author information, and uses the class name Byline. Here’s the relevant portion of markup:

<div class="Header">

<h1>How the World Could End</h1>

<p class="Teaser">Scenarios that spell the end of life as we know it

</p>

<p class="Byline">by Ray N. Carnation</p>

</div>

Next up is a rule that formats a <div> with the class name Content. It holds the main body of the page. The accompanying style sheet rule sets the font, padding, and line height:

.Content {

font-size: medium;

font-family: Cambria, Cochin, Georgia, "Times New Roman", Times, serif;

padding-top: 20px;

padding-right: 50px;

padding-bottom: 5px;

padding-left: 50px;

line-height: 120%;

}

Whereas the header rule set the padding to be the same on all sides, the content rule sets different padding on each side, adding more space above and the most space on the sides. One way to do that is to specify the expanded padding properties (like padding-top, padding-right, and so on), as done here. Another option is to use the padding property with a series of values in a particular order—top, right, bottom, left. Here’s how you can replace the expanded padding properties with just one property:

padding: 20px 50px 5px 50px;

Generally, you’ll use this form when setting the padding on all sides, but you’ll use the expanded padding properties if you want to change the padding on only certain sides. Of course, it’s really a matter of taste.

The final line-height property sets the space between adjacent lines. The value of 120% gives some extra spacing, for a more readable feel.

Following the content rule are three contextual selectors that format elements inside. The first rule formats a span with the class name LeadIn. It’s used to put the first two words in large, bold, small-cap lettering:

.Content .LeadIn {

font-weight: bold;

font-size: large;

font-variant: small-caps;

}

The next two rules change how the <h2> and <p> elements are formatted in the content region:

.Content h2 {

color: #24486C;

margin-bottom: 2px;

font-size: medium;

}

.Content p {

margin-top: 0px;

}

As you can see, as a style sheet grows longer it doesn’t necessarily become more complex. Here, the style sheet simply repeats the same basic techniques (class selectors and contextual selectors), but uses them to format other parts of the document.

Finally, the style sheet ends with the rules that format the footer portion. By now, you can interpret these on your own:

.Footer {

text-align: center;

font-size: x-small;

}

.Footer .Disclaimer {

font-style: italic;

}

.Footer p {

margin: 3px;

}

This rounds out the ApocalypsePage_Original.css style sheet. Feel free to download it from the try-out site (http://prosetech.com/html5) and try tweaking it to see what happens. Or, check out Chapter 2, which revises this page and the accompanying style sheet to use the HTML5 semantic elements.