Exploring CSS Grammar

CSS is a language and has clearly defined grammar. In this section, you’ll learn the components of a style rule. Style rules can be compared to a sentence: they have individual pieces, just like nouns and verbs that must exist in a specific order. In this section, you’ll learn about selectors (complex but primary building blocks within a rule), style properties, and how selectors and style properties combine to create rules. You’ll also learn to create classes—a custom means of applying style—understand the role of IDs, and how to use grouping, which is a form of CSS shorthand, to more easily write your rules.

Selectors

Selectors are CSS constructs that identify the elements within your markup that will receive the properties and values you assign. In CSS2, there are 14 kinds of selectors: the original seven from the CSS1 specifications with some modifications and an additional seven.

Note 

 Not all selector types are supported in all browsers. This section will provide you with the general information, and as you work through the book using different kinds of selectors, you’ll learn how to use them more explicitly. For a helpful chart on selector support, see www.webreview.com/style/css2/charts/selectors.shtml .

Element Selectors

An element selector refers directly to an HTML (or XHTML) element. So, the CSS selector h2 corresponds to any h2 element in the documents with which it is integrated.

Style sheets will typically begin with element selectors, because you are taking the document tree structure and denoting each element for which you’d like a style. You’ll create rules made up of other CSS components to go along with these selectors, and these rules will be placed in a declaration block. Here’s a selector and an empty declaration block:

h1  { }

If I have a simple document containing all the required elements and then some content style with h1, h2, h3 headers, paragraphs, and an unordered list, I could prepare a list of related CSS selectors along with declaration blocks, as follows:

body  { } h1  { } h2  { } h3  { } p  { } ul  { } li  { } 

As you can see, these element selectors look exactly like their corresponding HTML or XHTML elements, except they do not have the angle brackets surrounding them. Any rules written for these selectors will apply to all instances of the element unless another rule is in place for a particular selector.

Note 

 Declaration blocks in CSS always begin and end with a curly brace. Individual rules within a block are completed with a semicolon. The way blocks are authored will vary depending upon the preference of the author. Some authors prefer to write the selector and keep the declaration block all on one line (for example, h1 { }), whereas other authors fashion their style sheets to look similar to the method in this book.

Class Selectors

In CSS you can create class selectors, which provide you with infinitely more design options than an element selector. Class selectors are integrated into your documents using the class attribute within any opening tag of the element to which you’d like to apply the class. There are two variants of class selectors: general and specific.

A general class selector is any class you create denoted by a dot and then the class name. To create a class called “small” that will provide a smaller size text alternative for any element, I’d write the class:

.small

Later, once the associated rule is written (for example, .blue {font-size: 10px;}), I would then add the class attribute to the element I would like to influence:

<a >What’s new</a>

This paragraph will now appear with the rule associated with the class, .small. I can use this class anywhere that makes sense.

To apply the same presentational aspects of this class to a paragraph on my page, I’d write:

<p >This month finds us working on several important home projects. We’re ripping up the carpet on the stairs and replacing it with wood. It’s a lot of work, but the results are looking great!</p> 

My paragraph will now appear in the smaller style I created, but any other paragraphs or elements on the page will not, unless I use this class, or another style rule that defines the same font and size, with a given element.

A more specific way of writing class selectors is to relate them to an element selector. This means you can only apply the class to that particular element. You write these selectors by first denoting the element, then the class:

p.small

You can write as many specific classes for an element as you like; for example:

p.small  {      font-size: 10px; } p.medium  {      font-size: 12px; } p.large  {      font-size: 14px; }

And so forth. The main advantage to using a more specific class attribute is that it prevents any overlap. Specific rules can’t apply to an element for which they are not written. On the other hand, the flexibility of a general class can be a particularly powerful and streamlined approach to creating broad styles that can be applied to any element.

ID Selectors

ID selectors are quite similar to class selectors, but there are some differences—both semantic and behaviorally.

From a semantic perspective, ID selectors are written differently from class selectors. Instead of the dot (.) followed by the class name, you use a hash mark (#) followed by the ID name:

#section1

And, instead of using the class attribute, you use the id attribute when integrating the style into your HTML or XHTML document:

<div >This is the first division on my page.</div>

Behaviorally, the importance of IDs is that they relate to one element and one element only. While classes can be broadly or specifically applied, they can by nature refer to numerous elements. An ID is only allowed to be used once, as in the preceding example. What you should not do is the following:

<h1 >Welcome!</h1> <div >This is the first division on my page.</div>

Interestingly, many browsers will forgive you and still interpret your style rules if you do this. However, it’s bad form—not just because it goes against the syntax, but also because IDs are a critical piece of many dynamic events. If you inadvertently use multiple IDs with the same value, you can interfere with the proper interpretation of any dynamic content.

Contextual (Descendant) Selectors

You probably won’t be using this type of selector too much, but descendant selectors do provide a fine level of control if you’re looking to combine aspects of inherited style.

If you look at the earlier example of the parent-child relationship between a paragraph with an emphasis element within it, you’ll see how descendant selectors can work. In that example, the em element and its contents inherited the rule features from the parent element, p.

If you want to assign a different style rule to the descendant element, you can use the syntax provided by the descendant selector to do so. Place the parent element first, then the descendant element, with only a space between them:

p em

Then, whatever you write in the ensuing declaration block will apply to the descendant selector. Keep in mind that the rule specified for this selector won’t apply to any other em elements on the page, only those em elements that are descendants of paragraphs.

Pseudo Class Selectors

Used most frequently to style links, pseudo class selectors can also be used for other purposes, such as adding a hover effect to any element, whether it’s a link or not.

What’s especially powerful about pseudo class selectors when used with links is that you can combine these selectors with class selectors to create multiple link styles that can be applied to a single page—something you could never do with HTML or XHTML alone.

Link pseudo class selectors begin with the anchor selector, followed by a colon and the pseudo class name. The available conventional link pseudo class selectors are as follows:

a:link a:visited a:hover a:active

You can then write rules for each of these class selectors and they will apply globally to all normal links.

Note 

 The pseudo class selectors :active and :hover are also classified as "dynamic" pseudo classes, which are discussed in the "Dynamic Pseudo Class Selectors" section later in this chapter.

As mentioned, you can combine these selectors with a class, which enables you to create multiple link styles. To do this, you begin with the anchor, followed by a dot, then the class name, followed by the colon and pseudo class. Some examples include:

a.main:link a.subnav:link a.footer:link

In these examples, the links with the classes of main, subnav, and footer can each have different style rules created for them.

Note 

 If you have problems using link pseudo classes and find that aspects of your style aren’t applying properly, it’s possible that you are having trouble with specificity. Pseudo classes have an equal specificity between them and with HTML element selectors. This means that the selector occurring last will win out over the others. You must follow the link/visited/hover/active order of these selectors within your style sheet, or you may have unpredictable results.

Pseudo Element Selectors

Taking its cue from the print world, which has many conventions when it comes to displaying various typographic elements, CSS provides its authors with some means of grabbing on to these conventions.

As of CSS2, there are a total of four pseudo element selectors to assist you in achieving your typographic goals. Table 2.1 shows the four pseudo element selectors and describes their purpose.

Table 2.1: Pseudo Element Selectors in CSS2

Selector

Purpose

:first-line

To select and apply style to the first line in a given element

:first-letter

To select and apply style to the first letter in an element

:before

Allows content specified in the style sheet to be inserted before a given element

:after

Allows content specified in the style sheet to be inserted after a given element

To apply a different style to the first line in a paragraph, use the syntax for the pseudo element:

p:first-line

If you want to add content before or after an element, you need to define that content within the style sheet. This is an unusual quirk of CSS in that you’re actually placing content in the sheet, which goes against the main concept of separating presentation from the document and its structure and content! This process is referred to as generated content and the practice is not generally recommended because of this conflict.

Note 

 To learn more about generated content, please see www.w3.org/TR/REC-CSS2/generate.html.

To generate content using the before and after pseudo selectors, you define the element to which the rule should be applied, the before or after pseudo element, the content property, and the content in quotes:

h1:after  {      content: "header note" } 

In supporting browsers (which at this writing include only Opera and Gecko-based browsers), you’ll see the words “header note” appear after every h1 in the document.

Note 

 You cannot use any HTML or XHTML elements within the content value.

Selector Groups

Selector groups allow you to group selectors together that will all receive the same style. This provides a shorthand method for you, cutting down on authoring time, and ensures that these styles are applied consistently.

To make all headers have the same font, instead of writing individual rules for all the header levels in a document, you can group those elements by placing them all on one line, separated by commas:

h1, h2, h3 {font-family: Arial, sans-serif;}

Now the rule you apply to this group will correspond to all of those elements within the document.

Dynamic Pseudo Class Selectors

This rather cool selector type allows you to add pseudo selector intelligence to anything other than links, which of course have their own pseudo classes.

Table 2.2 shows the three available dynamic pseudo class selectors and their purpose.

Table 2.2: Dynamic Pseudo Class Selectors

Selector

Purpose

:hover

Applies the style rule only when the mouse hovers over the selected element

:active

Applies style when the element is clicked

:focus

Applies style when the element has the keyboard focus (such as when the cursor is placed in a form’s text box)

You can do some creative things with dynamic pseudo class selectors, especially with elements that are by nature interactive, such as forms. Using CSS this way instead of scripting is a very efficient way to achieve dynamic visual effects.

Note 

 As with pseudo class selectors, you can add a class selector to dynamic pseudo class selector for even richer options.

Language Pseudo Class Selectors

This fascinating selector helps to address language concerns, which is especially interesting in light of the work being done with internationalization, as discussed in Chapter 1.

Unfortunately, the support for this feature is currently limited, but with growing focus on internationalization-related topics, browser support should improve.

Note 

 For current browser tests with Language Pseudo Class Selectors, please see www.meyerweb.com/eric/css/tests/css2/.

In HTML and XHTML, you can denote an element as a specific language by using the lang attribute:

<p lang="es">Bienvenidos a todo!</p>

With language pseudo class selectors, you can now select an element based on its language encoding. You denote the selector, the :lang pseudo class selector, and the language value in parentheses:

p:lang(es)

Now you can provide styles for the language in question, which will be especially helpful for multilingual document presentation.

Note 

 You can find a list of language codes at www.oasis-open.org/cover/iso639a.html .

Child Selectors

Descendant (contextual) selectors allow you to style a child element separately from its parent. But what happens if you have deeply nested elements? For example, you can have numerous em elements in a division element, div, and paragraphs within that division can also have strong elements.

If you wrote the following descendant selector:

div strong

all of the strong elements within the div—even those within paragraph elements (the grandchildren)—would be affected due to inheritance.

Child selectors allow you to choose only the child. That means you can be sure that only the em elements within the div, and not those within other structures nested in the div, will be affected. To achieve this, you begin by using the element, a right angle bracket, and the child element in question:

div>em

You can get even more complex. If you want to choose only the em elements within the paragraph elements within the div, write the selector as follows:

div>p>em

All the children within a p element, but not outside of one, will be styled with the ensuing rule.

First Child Selectors

A first child selector allows even greater precision. This type of selector applies only to the first child of a given element. To apply a style to a first child only, supply the parent element plus the first child selector syntax:

p:first-child

Any rule you write for this selector will be applied to the first child of every paragraph only.

Note 

 Support for first child selectors is still very limited in browsers.

Adjacent Selectors

Adjacent selectors help you style sibling elements. Sibling elements are those elements that reside on the same level of a document tree and share a common parent. Consider the following:

<p>I find books by <a http://www.marthagrimes.com/">Martha Grimes</a> to be the quintessential escapist experience. A good mystery and a <a href="http://www.adagioteas.com/">cup of tea</a> on a rainy day is true relaxation.</p>

In this example, both anchor elements are siblings to one another because they share the parent element of the paragraph.

Styling an adjacent selector means being less concerned with the containment hierarchy, however, and more interested in the order of siblings within a parent element. An adjacent selector allows you to style one sibling that follows another. The syntax is to define the elements that are adjacent by using a plus sign (+):

th+td

With this example, you can create rules for your table headers and then describe a rule that uses the adjacent sibling selector to ensure that a table cell appearing right after a table header in the same row takes the defined style. And yes, there’s very poor browser support for adjacent selectors, too.

Attribute Selectors

This fascinating type of selector also has pretty weak support, but attribute selectors are powerful because they enable you to select elements based on the attributes they have. For example, if you have a link with a particular URL, you can style by that instead of by the anchor element itself. Every instance of that URL is then styled according to the rule associated with that attribute selector.

There are four matching patterns available for attribute selectors, as described in Table 2.3.

The level of control that can be gained by using this type of selector is quite amazing when you think about it. By providing a means of selecting based on an element’s attributes—and even going beyond to describe the selector based on attribute values—you can make complex decisions about how to efficiently style multiple element types within a document.

Table 2.3: Attribute Matching

Syntax

Purpose

[att]

Apply the style to a given attribute, no matter the value

[att=val]

Apply the style to a given attribute with a specific value

[att~=val]

Apply the style to any attributes with space-separated specified values

[att|=val]

Apply the style to any attributes with hyphen-separated values

Properties, Declarations, Rules

So far, you’ve examined a style sheet’s most basic relationship: selector to element or attribute. The connecting of a selector to an element or attribute is where CSS and markup become integrated, and there’s no doubt that selector types are a particularly complex aspect of CSS.

Fortunately, some relief comes with the way rules for selectors are created. It’s a pretty straightforward relationship at this point. Once you describe a selector, you add CSS properties. As a selector relates primarily to a given element, a property relates to the aspects you’d like that element to have. If you have a paragraph as a selector, properties you include within a rule help to describe the paragraph’s features.

Properties in CSS are numerous and fall into the following three general categories, based on their associated media group:

Visual Any properties influencing the visual representation of a document such as fonts, backgrounds, and colors.

Aural Properties relating to aural style, such as voice features.

Paged Properties relating to paged media such as print and screen.

As with literal attributes within markup, a property requires a name and a value. Here are two examples of CSS properties and a corresponding value:

font-family: Arial, sans-serif color: blue

A property and a value combine to create a declaration, as in the previous examples. A selector plus a declaration form a rule:

body  {      font-family: Arial, sans-serif; } 

Notice the syntax here: curly brackets to contain the declaration block (or multiple declarations) for the rule; semicolons ending each declaration. So, if you have multiple declarations within a rule, you separate them by semicolons:

body  {      font-family: Arial, sans-serif;      color: blue; }  

Note that my indentations are my personal style—as long as you follow the convention of placing the selector first, followed by declarations within brackets and each separated by a semicolon, you can find your own style of creating style! The previous CSS rule could just as easily be written like the following and still be perfectly correct:

body  {font-family: Arial; color: blue;} 

To summarize:

  • A declaration is made up of a property and a value.

  • A rule is comprised of a selector and a declaration block.

  • A style sheet contains at least one rule and can contain as many rules as you require.

You can find a listing of all the properties, their related values, and their media groups at www.w3.org/TR/REC-CSS2/propidx.html.

Shorthand Properties

Shorthand properties (also referred to as grouping) are a way to write a shorthand version of style rules. There are really only a few shorthand properties when compared to the full list of properties. Shorthand properties, the properties they can represent, and the media group(s) to which they belong are described in Table 2.4.

Table 2.4: Shorthand Properties in CSS2

Shorthand

Included Properties

Media Group

background

background-attachment

background-color

background-image

background-position

background-repeat

visual

border

border-color

border-style

border-width

visual

border-bottom

border-bottom-color

border-bottom-style

border-bottom-width

visual

border-left

border-left-color

border-left-style

border-left-width

visual

border-right

border-right-color

border-right-style

border-right-width

visual

border-top

border-top-color

border-top-style

border-top-width

visual

cue

cue-before

cue-after

aural

font

font-family

font-size

font-style

font-weight

font-variant

line-height

visual

list-style

list-style-image

list-style-position

list-style-type

visual

margin

margin-top

margin-right

margin-bottom

margin-left

visual

outline

outline-color

outline-style

outline-width

visual, interactive

padding

padding-top

padding-right

padding-bottom

padding-left

visual

pause

pause-after

pause-before

aural

You’ve already seen an example of shorthand when looking at grouped element selectors:

h1 h2 h3

You’ve also seen them with declarations:

p  {      font-family: Arial, sans-serif;      font-size: 16px;      font-weight: bold;      font-style: normal;      line-height: 15px;      color: black; }

Fortunately, you can choose to use the font property, which is a shorthand property, and stack the values within the declaration. As a result, you can make the previous rule a lot more streamlined:

p  {      font: bold normal 16px/15px Arial, sans-serif; }

The major concern when grouping is the order of values. A good example of this is when working with the margin property: you must follow the property with top, right, left, and bottom margin values in that order:

body  {      margin: .10in .75in. .75in. .10in; } 
Note 

 No commas appear between individual values when values are grouped. The declaration should end with a semicolon.

Commenting CSS

There’s a specific technique for creating comments in CSS, as well as a means of hiding embedded CSS from older browsers.

Comments in CSS begin with a slash (/) and an asterisk (*) and end with an asterisk and a slash:

/* add your comment here. The comment can be as long as you need it to be */

As with comments in HTML and XHTML, you can place these anywhere in the document and browsers will not seek to interpret what’s within them. However, do not use HTML and XHTML comments (<!-— —->) within the style sheet itself.

You can, however, use them within HTML and XHTML documents to “hide” embedded style from browsers with no CSS support. This is a widely used practice. Without the comments, browsers that don’t support the style element might try to render the style information even though the style information sits within the head portion of the document:

<head> <style type="text/css"> <!-— body  {      font-family: Arial;      color: blue; }  —-> </style> </head>

Many designers and developers are not worried about those few browsers out there that have this kind of issue and have dropped the practice of commenting out style sheets. In fact, there are a few early browsers that don’t deal well with comments, and those browsers may have rendering problems due to the comments and not the style.

Note 

 One limited but remaining concern is that some search engine technologies will index CSS as regular content unless it’s commented out. Because embedded sheets sit in the head of the document, the actual CSS could end up on the search results page rather than meta-information, or along with it.



Cascading Style Sheets(c) The Designer's Edge
ASP.NET 2.0 Illustrated
ISBN: 0321418344
EAN: 2147483647
Year: 2005
Pages: 86

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net