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 an override 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>This paragraph takes on the styles defined in å the warningText class</p>
<p>Only <span>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.

  • Share/Bookmark

Related posts:

  1. Types of CSS selectors In the previous example, the most basic style of selector...
  2. CSS shorthand for font properties The CSS properties discussed so far can be written in...
  3. Setting a default font and font color using CSS As mentioned earlier, the body start tag was historically used...

Related posts brought to you by Yet Another Related Posts Plugin.

Filed Under: CSS Basic

About the Author: I am designer and want to learn CSS

RSSComments (0)

Trackback URL

Leave a Reply

You must be logged in to post a comment.