CHAPTER 2
CSS Crash Course

The subject of Cascading Style Sheets (CSS) is a large one, covering a wide range of different techniques, and there are many books that have been written solely about how to use it and how it works. But in this chapter, I have distilled as much of this information as possible into an easily digestible primer that provides all the information you need to use the plug-ins in this book.

If you are already used to CSS, I recommend you at least skim through this chapter to get a quick refresher on the subject since the rest of the book draws on this information.

CSS Rules

Before looking at the inner workings of style sheets, let’s examine the structure of CSS and break down the rules for constructing CSS statements.

Each statement starts with a selector, which is what the rule affects. For example, in the following assignment, h1 is the selector being given a font size 240 percent larger than the default:

h1 { font-size:240%; }

By providing a new value to the font-size property of the selector, this ensures that the contents of all <h1> … </h1> pairs of tags will be displayed at a font size 240 percent larger than the default size. This is achieved by placing one or more assignments within the { and } symbols that follow the selector (in this case: font-size:240%;).

The part before the : (colon) symbol is the property, while the remainder is the value applied to it. Lastly, there is a ; (semicolon) to end the statement, which in this instance is not required (but would be if another assignment were to follow on the same line). For the sake of avoiding tricky to track down errors, in this book I always include the semicolons even when they are not necessary.

Multiple Assignments

You can create multiple property assignments in a couple of different ways. First, you can concatenate them on the same line, like this:

h1 { font-size:240%; color:blue; }

This adds a second assignment that changes the color of all <h1> headers to blue. You can also place the assignments one per line, like the following:

h1 { font-size:240%;
color:blue; }

Or you can space the assignments out a little more so they line up below each other in a column at the colons, like this:

h1 {
    font-size:240%;
        color:blue;
}

This way you can easily see where each new set of rules begins, because of the selector in the first column, and because the assignments that follow are neatly lined up with all property values starting at the same horizontal offset.

There is no right or wrong way to lay out your CSS, but I recommend you at least try to keep each block of CSS consistent with itself, so it can be easily taken in at a glance. This is the approach I have taken in this book, in that I always try to make groups of assignments as tidy and symmetrical as I can so the individual CSS rules are easy to follow.

Comments

It is a good idea to comment your CSS rules, even if you only describe the main groups of statements rather than all or most of them. You can do this in two different ways. First, you can place a comment within a pair of /* … */ tags, like this:

/* This is a CSS comment */

Or you can extend a comment over many lines, like this:

/* A Multi
   line
   comment */

CAUTION If you use multiline comments, you should be aware that you cannot nest more comments within them, otherwise you will get unpredictable errors.

Style Types

A number of different style types exist, ranging from the default styles set up by your browser (and any user styles you may have applied), through inline or embedded styles to external style sheets. The styles defined in each type have a hierarchy of precedence, from low to high.

Default Styles

The lowest level of style precedence is the default styling applied by a web browser. These styles are created as a fallback for when a web page doesn’t have any styles and are intended to be a generic set of styles that will display reasonably well in most instances.

Pre-CSS, these were the only styles applied to a document, and only a handful of them could be changed by a web page (such as font face, color and size, and a few element-sizing arguments).

User Styles

User styles are the next highest precedence of styles, and are supported by most modern browsers, but are implemented differently by each. If you would like to learn how to create your own default styles for browsing, use a search engine to enter your browser name followed by user styles (for example, enter firefox user styles for the Mozilla Firefox browser). Figure 2-1 shows a user style sheet being applied to Microsoft Internet Explorer 8 by clicking Internet Options | General | Accessibility.

image

FIGURE 2-1 Applying a user style sheet to Internet Explorer 8

If a user style is assigned that has already been defined as a browser default, it will then override the browser’s default setting. Any style not defined in a user style sheet will retain their default values as set up in the browser.

External Style Sheets

The next types of styles are those assigned in an external style sheet. These settings will override any assigned either by the user or by the browser. External style sheets are the recommended way to create your styles because you can produce different style sheets for different purposes, such as styling for general web use, for viewing on a mobile browser with a smaller screen, for printing purposes, and so on, and then apply just the one needed for each type of media.

Internal Styles

Internal styles are those you create within <style> … </style> tags; they take precedence over all the preceding style types. At this point, though, you are beginning to break the separation between styling and content since any external style sheets loaded in at the same time will have a lower precedence.

Inline Styles

An inline style is where you assign a property directly to an element. It also has the highest precedence of any style type. It is used like this:

<a href="http://google.com" style="color:green;">Visit Google</a>

In this example, the link specified will be displayed in green, regardless of any default or other color settings applied by any other type of style sheet, whether directly to this link or generically for all links.

When you use this type of styling, you are breaking the separation between layout and content; therefore, it is recommended you do so only when you have a very good reason.

Selectors

The means by which you access one or more elements is called selection, and the part of a CSS rule that does this is known as a selector. As you might expect, there are many different varieties of selector.

Type

The type selector works on types of HTML elements such as <p> or <i>. For example, the following rule will ensure that all the contents within <p> … </p> tags are fully justified:

p { text-align:justify; }
Descendant

Descendant selectors let you apply styles to elements that are contained within other elements. For example, the following rule sets all text within <b> … </b> tags to red, but only if they occur within <p> … </p> tags (like this: <p><b>Hello</b> there</p>):

p b { color:red; }

Descendant selectors can continue nesting indefinitely, so the following is a perfectly valid rule to make bold text within a list element of an unordered list display in blue:

ul li b { color:blue; }
Child

The child selector is similar to the descendant selector, but is more constraining about when the style will be applied by selecting only those elements that are direct children of another element. For example, the following code uses a descendant selector that will change any bold text within a paragraph to red, even if the bold text is itself within italics (like this <p><i><b>Hello</b> there</i></p>):

p b { color:red; }

In this instance, the word “Hello” displays in red. However, when this more general type of behavior is not required, a child selector can be used to narrow the scope of the selector. For example, the following child selector will set bold text to red only if the element is a direct child of a paragraph, and is not itself contained within another element:

p > b { color:red; }

Now the word “Hello” will not change color because it is not a direct child of the paragraph.

ID

If you give an element an ID name (like this: <div id=’mydiv’>), then you can directly access it from CSS in the following way, which changes all the text in the div to italic:

#mydiv { font-style:italic; }
Reusing IDs

IDs can be used only once within a document; therefore, only the first occurrence found will receive the new property value assigned by a CSS rule. But in CSS, you can directly reference any IDs that have the same name, as long as they occur within different element types, like this:

<div id='myid'>Hello</div>
<span id='myid'>Hello</span>

Because IDs normally apply only to unique elements, the following rule will apply an underline to only the first occurrence of myid:

#myid { text-decoration:underline; }

However, you can ensure that CSS applies the rule to both occurrences like this:

span#myid { text-decoration:underline; }
div#myid  { text-decoration:underline; }

Or more succinctly, like this (see the section on grouping a little further on):

span#myid, div#myid { text-decoration:underline; }

CAUTION If you use this form of selection, you should remember that any JavaScript that also must access these elements cannot easily do so because the commonly used getElementByID() function will return only the first occurrence. To reference any other instances, the programmer would have to search through the whole list of elements in the document, a cumbersome task to undertake.

Class

A much better way to reference multiple elements at a time is with a class. When you want to share the styling of a number of elements in a page, you can assign them all the same class name (like this: <span class=’myclass’>) and then create a single rule to modify all those elements at once, as in the following rule, which creates a 10-pixel left-margin offset for all elements using the class:

.myclass { margin-left:10px; }

In modern browsers, HTML elements may also use more than one class by separating them with spaces, like this: <span class=’thisclass thatclass otherclass’>, which is the technique used in this book to provide multiple styles to elements. Older browsers only allow a single class, so if you are targeting them, you should put the most important class first.

Narrowing Class Scope

You can narrow the scope of action of a class by specifying the types of elements to which it should apply. For example, the following rule applies the setting only to paragraphs that use the class main:

p.main { text-indent:30px; }

In this example, only paragraphs using the class main (like this: <p class=“main”>) will receive the new property value. Any other element types that may try to access the class (such as <div class=”main”>) will be ignored.

Attribute

Many HTML tags support attributes and using this type of selector can save you from having to use IDs and classes for referencing them. For example, you can directly reference attributes in the following manner, which sets all elements with the attribute type=“submit” to a width of 100 pixels:

[type="submit"] { width:100px; }

If you wish to narrow the scope of the selector to, for example, only form input elements with that attribute type, you could use the following rule instead:

form input[type="submit"] { width:100px; }

NOTE Attribute selectors also work on IDs and classes so that, for example, [class=“classname”] performs in exactly the same way as the ID selector .classname (except that the latter has a higher precedence). Likewise, [id=“idname”] is equivalent to using the class selector .idname. The # and . prefaced class and ID selectors can, therefore, be viewed as shorthand for attribute selectors, but with a higher precedence.

Universal

The wildcard or universal selector matches any element, so the following rule will make a complete mess of a document by giving a green border to all of its elements:

* { border:1px solid green; }

It’s therefore unlikely that you will use the * on its own, but as part of a compound rule it can be very powerful. For example, the following rule will apply the same styling as earlier, but only to all paragraphs that are subelements of the element with the ID boxout, and only as long as they are not direct children:

#boxout * p {border:1px solid green; }

Here, the first selector following #boxout is a * symbol, and so it refers to any element within the boxout object. The following p selector then narrows down the selection focus by changing the selector to apply only to paragraphs (as defined by the p) that are subelements of elements returned by the * selector. Therefore, this CSS rule performs the following actions (in which I use the terms object and element interchangeably to refer to the same thing):

1. Finds the object with the ID of boxout.

2. Finds all subelements of the object returned in step 1.

3. Finds all p subelements of the objects returned in step 2 and, since this is the final selector in the group, also finds all p sub- and sub-subelements (and so on) of the objects returned in step 2.

4. Applies the styles within the { and } characters to the objects returned in step 3.

The net result of this is that the green border is applied only to paragraphs that are grandchildren (or great-grandchildren, and so on) of the main element.

Grouping

Using CSS, it is possible to apply a rule to more than one element, class, or any other type of selector at the same time by separating the selectors with commas. So, for example, the following rule will place a dotted orange line underneath all paragraphs, the element with the ID of idname, and all elements using the class classname:

p, .idname, #classname { border-bottom:1px dotted orange; }

The Cascade

One of the most fundamental things about CSS properties is that they cascade, which is why they are called Cascading Style Sheets. But what does this mean? Well, cascading is a method used to resolve potential conflicts between the various types of style sheet a browser supports, and apply them in order of precedence according to who created them, the method used to create the style, and the types of properties selected.

Style Sheet Creators

Three main types of style sheet are supported by all modern browsers. In order of precedence from high to low, they are:

1. Those created by a document’s author

2. Those created by the user

3. Those created by the browser

These three sets of style sheets are processed in reverse order. First, the defaults in the web browser are applied to the document. Without these defaults, web pages that don’t use style sheets would look terrible. They include the font face, size and color, element spacing, table borders and spacing, and all the other reasonable styling a user would expect.

Next, if the user has created any user styles to employ in preference to the standard ones, these are applied, replacing any of the browser’s default styles that may conflict.

Lastly, any styles created by the current document’s author are then applied, replacing any that have been created either as browser defaults or by the user.

Style Sheet Methods

Style sheets can be created in three different ways, or methods. In high to low order of precedence, they are:

1. As inline styles

2. In an embedded style sheet

3. As an external style sheet

Again, these methods of style sheet creation are applied in reverse order of precedence. Therefore, all external style sheets are processed first, and their styles are applied to the document.

Next, any embedded styles (within <style> … </style> tags) are processed, and any that conflict with external rules are given precedence and override the others.

Lastly, any styles applied directly to an element as an inline style (such as <div style=“…”> … </div>) are given the highest precedence, and override all previously assigned properties.

Style Sheet Selectors

Selecting elements to be styled is done in three different ways. Going from highest to lowest order of precedence, they are:

1. Referencing by individual ID

2. Referencing in groups by class

3. Referencing by element tags (such as <p> or <b>)

Selectors are processed according to the number and types of elements affected by a rule, which is a little different than the previous two methods for resolving conflicts. This is because rules do not have to apply only to one type of selector at a time, and may reference many different selectors. Therefore, a method is needed to determine the precedence of rules that can contain any combination of selectors. This is done by calculating the specificity of each rule by ordering them from the widest to narrowest scope of action.

This specificity is calculated by creating three-part numbers based on the selector types in the earlier numbered list. These compound numbers start off looking like [0, 0, 0]. When processing a rule, each selector that references an ID increments the first number by 1, so that the compound number would become [1, 0, 0]. Let’s say there are three ID references in a particular rule; thus, the compound number becomes [3, 0, 0].

Then, the number of selectors that reference a class is placed in the second part of the compound number. Let’s say there were five of them, making the number [3, 5, 0].

Finally, all selectors that reference element tags are counted and this number is placed in the last part of the compound number. Let’s say there were two, so the final compound number becomes [3, 5, 2], which is all that is needed to compare this rule’s specificity with any another.

In cases with nine or fewer of each type in a compound number, you can convert it directly to a decimal number, which in this case is 352. Rules with a lower number than this will have lower precedence, and those with a higher number will have greater precedence. Where two rules share the same value, the most recently applied one wins.

Using a Different Number Base

Where there is more than nine of a type in a number, you have to work in a higher number base. For example, the compound number [11, 7, 19] doesn’t convert to decimal by simply concatenating the three parts. Instead, you can convert the number to a higher base, such as base 20 (or higher if there are more than 19 of any type).

To do this, multiply the three parts out and add the results like this, starting with the rightmost number and working left:

            20×19 =    380
          20×20×7 =   2800
      20×20×20×11 =  88000
 Total in decimal =  91180

On the left, replace the values of 20 with the base you are using, then once all the compound numbers of a set of rules are converted from this base to decimal, it is easy to determine the specifity, and therefore the precedence of each. Thankfully, all this is handled for you by the CSS processor, but knowing how it works helps you to properly construct rules and understand what precedence they will have.

The !important Tag

Where two or more style rules are equivalent, only the most recently processed rule will take precedence. However, you can force a rule to a higher precedence than other equivalent rules using the !important tag, like this:

p { color:#ff0000 !important; }

When you do this, all previous equivalent settings are overridden (even ones using !important) and any equivalent rules that are processed later will be ignored. So, for example, the second of the two following rules would normally take precedence, but because of the use of !important in the prior assignment, it is ignored:

p { color:#ff0000 !important; }
p { color:#ffff00 }

The Difference between Divs and Spans

Both divs and spans are types of containers, but they have different qualities. By default, a div has infinite width (at least to the browser edge), which can be seen by applying a border to one, like this:

<div style="border:1px solid green;">Hello</div>

A span, however, is only as wide as the text it contains. Therefore, the following line of HTML shows the border only around the word “Hello,” and it does not extend to the right-hand edge of the browser:

<span style="border:1px solid green;">Hello</span>

Also, spans follow text or other objects as they wrap around and can therefore have a complicated border. For example, in the following web page, CSS has been used to make the background of all divs yellow, all spans cyan, and to add a border to both before creating a few example spans and divs:

<html
   <head>
      <title>Div and span example</title>
         <style>
            div, span { border:1px solid black;  }
            div       { background-color:yellow; }
            span      { background-color:cyan;   }
         </style>
    </head>
    <body>
       <div>This text is within a div tag</div> This isn't.
       <div>And this is again.</div><br />

       <span>This text is inside a span tag.</span> This isn't.
       <span>And this is again.</span><br /><br />

       <div>This is a larger amount of text in a div that
       wraps around to the next line of the browser</div><br />

       <span>This is a larger amount of text in a span that
      wraps around to the next line of the browser</span>
   </body>
</html>

Figure 2-2 shows what this page looks like in a web browser. Although it is printed only in shades of gray in the paperback version of this book, the figure clearly shows how divs extend to the right-hand edge of a browser and force following content to appear at the start of the first available position below them.

The figure also shows how spans keep to themselves and only take up the space required to hold their contents, without forcing following content to appear below them. For example, in the bottom two examples of the figure, you can also see that when divs wrap around the screen edge, they retain a rectangular shape, whereas spans simply follow the flow of the contents within them.

image

FIGURE 2-2 A variety of divs and spans of differing widths

Therefore, since divs can only be rectangular, they are better suited for containing objects such as images, boxouts, quotes, and so on, while spans are best used for holding text or other attributes that follow one after another inline (such as sections of text).

Measurements

CSS supports an impressive range of different units of measurement, enabling you to tailor your web pages precisely to specific values or relative dimensions. The ones I generally use (which you will likely find the most useful) are pixels, points, ems, and percent.

• Pixels The size of a pixel varies according to the dimensions and pixel depth of the user’s monitor. One pixel equals the width/height of a single dot on the screen, and so this measurement is best suited to monitors.
Example: #classname { margin:5px; }

• Points A point is equivalent in size to 1/72 of an inch. The measurement comes from a print design background and is best suited for that medium, but is also commonly used on monitors.
Example: #classname { font-size:14pt; }

• Inches An inch is the equivalent of 72 points and is also a measurement type best suited for print.
Example: #classname { width:3in; }

• Centimeters Centimeters are another unit of measurement best suited for print. One centimeter is a little over 28 points.
Example: #classname { height:2cm; }

• Millimeters A millimeter is one-tenth of a centimeter (or almost 3 points). Millimeters are another measure best suited to print.
Example: #classname { font-size:5mm; }

• Picas A pica is another print typographic measurement, which is equivalent to 12 points.
Example: #classname { font-size:1pc; }

• Ems An em is equal to the current font size and is, therefore, one of the more useful measurements for CSS since it is used to describe relative dimensions.
Example: #classname { font-size:2em; }

• Exs An ex is also related to the current font size; it is equivalent to the height of a lowercase letter “x”. This is a less popular unit of measurement and is typically used as a good approximation for helping set the width of a box that will contain some text.
Example: #classname { width:20ex; }

• Percent This unit is related to the em in that it is exactly 100 times greater (when used on a font). Whereas 1 em equals the current font size, the same size is 100 in percent. When not relating to a font, this unit is relative to the size of the container of the property being accessed.

Example: #classname { height:120%; }

Fonts

Using CSS, you can style four main font properties: family, style, size, and weight. Between them, you can fine-tune the way text displays in your web pages and/or when printed, and so on.

Font Family

The font-family property assigns the font to use. It also supports listing a variety of fonts in order of preference so that styling can fall back gracefully when the user doesn’t have the preferred font installed. For example, to set the default font for paragraphs, you might use a CSS rule such as this:

p { font-family: Verdana, Arial, Helvetica, sans-serif; }

Where a font name is made up of two or more words, you must enclose the name in quotation marks, like this:

p { font-family: "Times New Roman", Georgia, serif; }

TIP Because they should be available on virtually all web browsers and operating systems, the safest font families to use on a web page are Arial, Helvetica, Times New Roman, Times, Courier New, and Courier. The Verdana, Georgia, Comic Sans MS, Trebuchet MS, Arial Black, and Impact fonts are safe for Mac and PC use, but may not be installed on other operating systems such as Linux. Other common but less safe fonts are Palatino, Garamond, Bookman, and Avant Garde. If you use one of the less safe fonts, make sure you offer fallbacks of one or more safer fonts in your CSS, so your web pages will degrade gracefully on browsers without your preferred fonts.

Font Style

With this property, you can choose to display a font normally, in italics or obliquely. The following rules create three classes (normal, italic, and oblique) that can be applied to elements to create these effects:

.normal  {font-style:normal;  }
.italic  {font-style:italic;  }
.oblique {font-style:oblique; }
Font Size

As described in the earlier section on measurements, you can change a font’s size in many ways. But these all boil down to two main types: fixed and relative. A fixed setting looks like the following rule, which sets the default paragraph font size to 14 point:

p { font-size:14pt; }

Alternatively, you may wish to work with the current default font size, using it to style various types of text such as headings. In the following rules, relative sizes of some headers are defined, with the <h4> tag starting off 20 percent bigger than the default, and with each larger size being another 40 percent larger than the previous one:

h1 { font-size:240%; }
h2 { font-size:200%; }
h3 { font-size:160%; }
h4 { font-size:120%; }
Font Weight

Using this property, you can choose how boldly to display a font. The main values you will use are likely to be normal and bold, like this:

.bold { font-weight:bold; }

Text

Regardless of the font in use, you can further modify the way text displays by altering its decoration, spacing, and alignment. A crossover exists between the text and font properties though, such that effects like italics or bold text are achieved via the font-style and font-weight properties, while others such as underlining require the text-decoration property.

Decoration

With the text-decoration property, you can apply effects to text such as underline, line-through, overline, and blink. For example, the following rule creates a new class called over that applies overlines to text (the weight of over, under, and through lines will match that of the font):

.over { text-decoration:overline; }
Spacing

A number of different properties allow you to modify line, word, and letter spacing. For example, the following rules change the line spacing for paragraphs by modifying the line-height property to be 25 percent greater, the word-spacing property is set to 30 pixels and letter-spacing is set to 3 pixels:

p {
   line-height    :125%;
   word-spacing   :30px;
   letter-spacing :3px;
}
Alignment

Four types of text alignment are available in CSS: left, right, center, and justify. In the following rule, default paragraph text is set to full justification:

p { text-align:justify; }
Transformation

Four properties are available for transforming text: none, capitalize, uppercase, and lowercase. For example, the following rule creates a class called upper that will ensure all text is displayed in uppercase when it is used:

.upper { text-transform:uppercase; }
Indenting

Using the text-indent property, you can indent the first line of a block of text by a specified amount. For example, the following rule indents the first line of every paragraph by 20 pixels, although a different unit of measurement or a percent increase could also be applied:

p { text-indent:20px; }

Colors

Colors can be applied to the foreground and background of text and objects using the color and background-color properties (or by supplying a single argument to the background property). The colors specified can be one of the named colors (such as red or blue), colors created from hexadecimal RGB triplets (such as #ff0000 or #0000ff), or colors created using the rgb() CSS function.

The standard 16 color names as defined by the W3C (w3.org) standards organization are aqua, black, blue, fuchsia, gray, green, lime, maroon, navy, olive, purple, red, silver, teal, white, and yellow. The following rule uses one of these names to set the background color for an object with the ID of object.

#object { background-color:silver; }

In the following rule, the foreground color of text in all divs is set to yellow (because on a computer display hexadecimal levels of ff red, plus ff green, plus 00 blue creates the color yellow):

div { color:#ffff00; }

Or, if you don’t wish to work in hexadecimal, you can specify your color triplets using the rgb() function, as in the following rule, which changes the background color of the current document to aqua.

body { background-color:rgb(0, 255, 255); }

TIP If you prefer not to work in ranges of 256 levels per color, you can use percentages in the rgb() function instead, with values from 0 to 100, ranging from the lowest (zero) amount of a primary color, through to the highest (100), like this: rgb(58%, 95%, 74%). You can also use floating point values for even finer color control, like this: rgb(23.4%, 67.6%, 15.5%).

Positioning Elements

Elements within a web page fall where they are placed in the document, but can be moved about by changing an element’s position property from the default of static to one of absolute, relative, or fixed.

An element with absolute positioning is removed from the document and any other elements that can will flow into its released space. You can then position the object anywhere you like within the document using the top, right, bottom, and left properties. It will then rest on top of (or behind) other elements.

So, for example, to move an object with the ID of object to the absolute location of 100 pixels down from the document start and 200 pixels in from the left, you would apply the following rules to it (you can also use any of the other units of measurement supported by CSS):

#object {
   position:absolute;
   top      :100px;
   left     :200px;
}

Likewise, you can move the object relative to the location it would occupy in the normal document flow. So, for example, to move object 10 pixels down and 10 pixels to the right of its normal location, use the following rules:

#object {
   position:relative;
   top      :10px;
   left     :10px;
}

The final positioning property setting lets you move an object to an absolute location, but only within the current browser viewport. Then, when the document is scrolled, the object remains exactly where it has been placed, with the main document scrolling beneath it—this is a great way to create dock bars and other similar devices. For example, to fix the object to the top left corner of the browser window, use the following rules:

image

FIGURE 2-3 Creating a simple dock bar using the position property

#object {
   position:fixed;
   top      :0px;
   left     :0px;
}

Figure 2-3 shows a simple dock bar created using a value of fixed for the position property to align the icons at the screen bottom. With a little JavaScript or proprietary CSS transforms, the icons can be made to resize as the mouse passes over them, as is happening to the second icon. See my book Plug-in JavaScript (McGraw-Hill Professional, 2010) for this and many other neat JavaScript plug-ins.

Pseudo Classes

A number of selectors and classes, used only within a style sheet, do not have any matching tags or attributes within any HTML. Their task is to classify elements using characteristics other than their name, attributes, or content that cannot be deduced from the document tree. These include pseudo classes such as first-line, first-child, and first-letter.

Pseudo classes are separated from elements using a : (colon) character. To create a class called bigfirst for emphasizing the first letter of an element, you would use a rule such as the following:

.bigfirst:first-letter {
   font-size:400%;
   float    :left;
}

When the bigfirst class is applied to an element, the first letter’s display size is much enlarged, with the remaining text (at normal size) neatly flowing around it (due to the float property), as if the first letter were an image or other object.

Other pseudo classes include hover, link, active, and visited, all of which are mostly useful for applying to anchor elements, as in the following rules, which set the default color of all links to blue, and that of links that have already been visited to light blue:

a:link    { color:blue;      }
a:visited { color:lightblue; }

The following pair of rules is interesting in that it uses the hover pseudo class, meaning they are applied only when the mouse is placed over the element and, in this example, they change the link to white text on a red background, providing a dynamic effect you would normally only expect from using JavaScript code:

a:hover {
   color     :white;
   background:red;
}

Here I have used the background property with a single argument, instead of the longer background-color property. The active pseudo class is also dynamic in that it effects a change to a link during the time between the mouse button being clicked and released—as with this rule, which changes the link color to dark blue:

a:active { color:darkblue; }

Another interesting dynamic pseudo class is focus, which is applied only when an element is focused by the user selecting it with the keyboard or mouse, as with the following rule, which uses the universal selector to always place a mid-gray, dotted, 2-pixel border around the currently focused object:

*:focus { border:2px dotted #888888; }

Shorthand

To save space, groups of related CSS properties can be concatenated into a single shorthand assignment. For example, I have already used the shorthand for creating a border a few times, as in the focus rule in the previous section, which is actually a shorthand concatenation of the following rule set:

*:focus {
   border-width:2px;
   border-style:dotted;
   border-color:#888888;
}

When using a shorthand rule, you need only apply the properties up to the point where you wish to change values. So you could use the following to set only a border’s width and style, but not its color:

*:focus { border:2px dotted; }

The Box Model

The fundamental CSS properties affecting the layout of a page are based around the box model; a nested set of properties surrounding an element, as shown in Figure 2-4.

Virtually all elements have (or can have) these properties, including the document body, whose margin you can, for example, remove with the following rule:

body { margin:0px; }

Once you have the hang of the box model, you will be well on your way to creating professionally laid out pages, since these properties alone will make up much of your page styling.

Margin

The margin is the outermost level of the box model. It separates elements from each other and its use is quite smart. For example, assume you have chosen to give a number of elements a default margin of 10 pixels around them. When placed on top of each other, this would create a gap of 20 pixels due to adding the border widths together.

However, to overcome this potential issue, when two elements with borders are directly one above the other, only the larger of the two margins is used to separate them. If both margins are the same width, just one of the widths is used. This way, you are much more likely to get the result you want. You should note, however, that the margins of absolutely positioned or inline elements do not collapse.

The margins of an element can be changed en-masse with the margin property, or individually with margin-left, margin-top, margin-right, and margin-bottom.

image

FIGURE 2-4 The nested levels of the CSS box model

When setting the margin property, you can supply one, two, three, or four arguments which have the effects commented in the following rules:

margin:1px;             /* Set all margins to 1 pixel width           */
margin:1px 2px;         /* Set the top and bottom margins to 1 pixel
                           and the left and right to 2 pixels width   */
margin:1px 2px 3px;     /* Set the top margin to 1 pixel, the left
                           and right to 2 pixels and the bottom
                           margin to 3 pixels width                   */
margin:1px 2px 3px 4px; /* Set the top margin to 1 pixel, the right
                           to 2 pixels, the bottom to 3 pixels and
                           the left margin to 4 pixels width          */
Border

The border level of the box model is similar to the margin except that there is no collapsing. The main properties used to modify borders are border, border-left, border-top, border-right, and border-bottom, and each of these can have other subproperties added as suffixes, such as –color, –style, and –width.

The four ways of accessing individual property settings used for the margin property also apply with the border-width property, so all the following are valid rules:

border-width:1px;             /* All borders                  */
border-width:1px 2px;         /* Top/bottom and left/right    */
border-width:1px 2px 3px;     /* Top, left/right and bottom   */
border-width:1px 2px 3px 4px; /* Top, right, bottom and left  */
Padding

The deepest of the box model levels is the padding, which is applied inside any borders and/or margins. The main properties used to modify padding are padding, padding-left, padding-top, padding-right, and padding-bottom.

The four ways of accessing individual property settings used for the margin and border properties also apply to the padding property, so all the following are valid rules:

padding:1px;             /* All borders                  */
padding:1px 2px;         /* Top/bottom and left/right    */
padding:1px 2px 3px;     /* Top, left/right and bottom   */
padding:1px 2px 3px 4px; /* Top, right, bottom and left  */
Content

Deep within the box model levels, at their center, lies an element that can be styled in all the ways discussed in this chapter, and which can (and usually will) contain further subelements. They in turn may contain sub-subelements and so on, each with their own styling and box model settings.

Summary

Although it has covered only a subset of CSS (there are many, many more aspects to the language than could ever be properly discussed in a single chapter), there is enough here to help you understand all the plug-ins in this book and modify them to your own requirements. You should also find this chapter a handy reference as your skills develop.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.11.226