Tuesday, September 14, 2010

Creating alternatives with classes and spans

It’s common in web design to define alternatives to the rules set for tag selectors (h1, h2,
p, etc.). This tends to happen most often in one of two situations. The first is when creating
alternate styles for a portion of a web page (as in print, it’s often beneficial to use
different text for sidebars and boxouts—standalone boxes on a magazine page, either
housing supplementary information to the main article, or an entirely independent piece
that needs to be visually distinct from other content on the page—and sidebars to ensure
that each area of content is easy to distinguish from another). In this situation, it’s sensible
to define a default rule for each element using an element selector, and then create anoverride for the portion of the page that requires different text by using a contextual
selector.
For example, imagine a typical web page that has a sidebar that’s marked up as a div with
an id value of sidebar. You might use a different paragraph font in the sidebar, to differentiate
the text, like so:
p {
font: 1.2em/1.5 Verdana, Arial, sans-serif;
margin-bottom: 1em;
}
#sidebar p {
font: 1.2em/1.5 Arial, sans-serif;
}
The other occasion where alternatives are required is when creating one-off styles to override
an existing style. In such cases, you can define a class in the CSS and then use a class
attribute to apply it to an element. Should you only want a portion of some text to take on
the style, you can surround the selection with a span element and apply the class to that
instead.
For example, if you wanted to create some “warning” text, you could use the following
CSS:
.warningText {
color: #ff0000;
font-size: 120%;
}
This can then be applied as follows:
<p class="warningText">This paragraph takes on the styles defined in
å the warningText class</p>
<p>Only <span class="warningText">this portion</span> of this
å paragraph takes on the warningText class styles.</p>
Avoid overusing span elements, though. Text works best when it’s consistent across the
page.
 

**Note that the preceding CSS style has a capital letter halfway through it—this case is
known as lowerCamelCase, and is a method of writing multiple-word style names,
because underscores and spaces must be avoided in CSS. Take care if you do this,
because styles are case sensitive. If you set a class attribute value to warningtext
instead of warningText, many browsers fail to display the style, reverting to the
default style for the relevant element.

No comments:

Post a Comment