Web Development

Group and contextual styles

There are a few ways to make CSS easier and more powerful, such as using contextual selectors, grouping selectors, and coding in shorthand. Here's how.

By Matt Rotter, Charity Kahn, and Paul Anderson

There's more to CSS than defining styles and adding them to your HTML documents. Here are a few ways to make CSS easier and more powerful.

Using contextual selectors

You can nest elements in a selector to create more specific styles:

STRONG EM { color: red }

This kind of selector is called a contextual selector, because text coded with an <EM> element will be colored red only in the context of the <STRONG> element; in other words, when nested inside it:

<STRONG>This is bold text, and <EM>this is bold, italic red</EM>.</STRONG>
<EM>This text is just italic.</EM>

Grouping selectors

You can also group selectors that share styles to reduce the size and redundancy of a style sheet. Just separate them with commas:

H1, STRONG EM, TD {
     font-family: Arial;
     color: blue;
}

Now all the elements (<H1>, <EM>, text within a <STRONG> element, and <TD>) will use the same style of formatting (blue, Arial text). Of course, that's in addition to what they retain from their original HTML definition; for example, <H1> retains its size, and <STRONG> retains its boldface. And text that isn't surrounded by any of these elements is unaffected by the style.

If you want to give one of these selectors additional formatting, simply define it again:

H1, STRONG EM, TD {
     font-family: Arial;
     color: blue
     }

H1 { font-style: italic }

Here, all these elements will be in blue Arial text, but <H1> will also be italic.

Coding in shorthand

You can also use shorthand in the style definition itself; for instance:

EM {font: 12pt/14pt bolder Arial, Helvetica}

is shorthand for

EM {font-family: Arial, Helvetica;
font-size: 12pt;
line-height: 14pt;
font-weight: bolder
}

(Note: some of these properties--for example, line-height--are holdovers from print publishing.)

Using <A> pseudoclasses

Pseudoclasses can also extend CSS to include properties of elements that aren't part of the HTML specification but that are supported by the browsers. For instance, the <A> element does not have link, active, or visited attributes, but the browsers support different colors for links depending on their state. You can define <A> pseudoclasses using the colon character:

A:link {color: red}
A:visited {color: blue}
A:active {color: white}

This colors unvisited links red, visited links blue, and active links (those being clicked) white. See the W3C recommendation for more on <A> pseudoclasses.

Matt Rotter and Charity Kahn are software engineers for CNET.com.

Paul Anderson is an associate technical editor for CNET Builder.com.
0 comments

Editor's Picks