Comments
Gabor Liptak wrote: Please share an invite at gl2002 [@] freemail.hu Thank you
Cloud Expo on Google News

SYS-CON.TV

2009 East
PLATINUM SPONSORS:
IBM
Smarter Business Solutions Through Dynamic Infrastructure
IBM
Smarter Insights: How the CIO Becomes a Hero Again
Microsoft
Windows Azure
GOLD SPONSORS:
Appsense
Why VDI?
CA
Maximizing the Business Value of Virtualization in Enterprise and Cloud Computing Environments
ExactTarget
Messaging in the Cloud - Email, SMS and Voice
Freedom OSS
Stairway to the Cloud
Sun
Sun's Incubation Platform: Helping Startups Serve the Enterprise
POWER PANELS:
Click For 2008 West
Event Webcasts
The Power of your Descendants
The Power of your Descendants

If you've decided this is the year you'll really get a handle on CSS, one of the first things you want to learn to do is harness its power - and avoid "classitis." Understanding the document tree - the structure of the document and the relationships between the elements - is the first step in writing highly efficient and compact CSS.

A mistake that many of us make when learning to use CSS is to put classes on most everything in the document to provide the specific styling desired. A bad case of classitis is hardly better than putting font tags everywhere. Yes, you're beginning to separate structure from presentation, but it's hardly elegant and efficient. Let's begin this exercise by looking at a simple hierarchy in the body area of an X/HTML document. First we'll look at the code, then the document tree (see Code I).

The hierarchy of the document tree can be demonstrated very much like a family tree. The example in Code I could appear graphically in the manner shown in Image I.

Notice that the hierarchy begins with the body element - much like your great grandparents might begin a portion of your family tree. From the body element descend the two divs - #content and #side. From #content descend the h1, p, and ul elements and it continues the same way throughout the document from there. The beauty of understanding the ancestral tree of your document is the ability it gives you to take advantage of the relationships that exist between elements in writing your CSS selectors. Instead of giving the various elements different classes, you can leave your X/HTML portion clean and simple and write a descendant selector. (Don't be confused. Descendant selectors were called contextual selectors in CSS1.)

A descendant selector is simply a list of other selectors, in order of their appearance in the document tree, separated by spaces. The selectors used to create the descendant selector can be any of the following types:

  1. Type selectors: A type selector is simply the redefinition of an element in your document. For example, if you write a CSS selector called ul, the attributes you write for that selector will apply to every ul element in your document. These selectors are the first thing I write when beginning to code a new site.
  2. ID selectors: An ID can be given to any element in your document. To write succinct, clean CSS, I generally apply my IDs to containers on the page, whether they're divs or tables. An ID can only be applied once on a page. (See my article, Persistent Page Indicator, at nemesis1.f2o.org/aarchive?id=9 for an example of practical uses for an ID indicating the down state of a menu button. Especially if you enjoy using Dreamweaver templates.)
  3. Class selectors: A class selector can be applied numerous times in a document. I generally use a class after I've redefined my elements (type selectors), defined my page area containers (IDs), and created all descendant selectors. Anything that falls outside those areas receives a class if needed.
Using our original X/HTML, let's look at an example of this. Since this article is about descendant selectors, I won't go into detail about the selectors I'm writing except to point out what kind they are. As mentioned previously, I always start with my type selectors. In this small document, I will only include the body type selector. I've given it the very basics (example files, if you'd like to work along, as well as the links used throughout this article are available from www.violetsky.net/mxdev/descend). Next, I move to the ID selectors for my containers. This will include #side and #content. I define their placement using those selectors. Now it's time for the descendants.

If you're following along and viewing the exercise in a browser, you likely noticed in the text of Code I that certain sentences are to be in color. Of course if you're following this exercise in a browser, it's obvious that at this point, they're all black. Many people would wrap those sentences in a <span> and give them a class. But there's no need for all that extra code. We've got the power of the descendants at our beck and call. Notice that in the first paragraph of the #content div, there's a sentence wrapped in a strong element. We'll use a descendant selector to color it orange. The descendant selector will begin with the highest level descendant and move in to the element we're styling (each separated by a space). Notice in the graphical example above, the strong element we want to give the orange color to descends from the p element. You could write the following selector:


p strong {
	color: #C30;
}

If you view this in your browser, you'll see why this won't give us the results we want on this page. All strong elements descending from p elements are now orange. Since that combination exists in the #side div, that sentence is now orange as well, an undesired result. We need to be more specific in our descendant. Here's the descendant selector that will work in our page:


#content p strong {
	color: #C30;
}

Due to the specificity in the previous example, the strong element in the #side div is now black again. We could have written a simple type selector for the h1 element. I chose instead to put the font sizing into the selectors for the div containers and thus, due to specificity which we'll discuss here later, I need to create the h1 selector as a descendant of the #content div. It was written as #content h1 so that it would override the sizing placed on the #content div.

Let's look at the other example in the unordered list. Using the principle we just learned, take a guess at the selector that could be written before you read on.


#content ul strong {
	color: #036;
}

You could have also written - #content ul li strong to be even more specific. Either will work. Why would you want to be more specific? Glad you asked. Many times you'll hear that if you want one selector to override another, simply put it later in the CSS cascade. That's not completely true. The W3C has set up a formula for the calculation of a selector's specificity (www.w3.org/TR/REC-CSS2/cascade.html#specificity). In a nutshell, the ID selectors have the highest value, followed by classes and pseudo-classes and last/least are the type selectors. You can read the guidelines at the above URI learn how to calculate them, but keeping the above principles in mind will likely guide you through the more simple combinations.

To experiment with the specificity idea, create both of the above selectors - #content ul li strong and #content ul strong. Create them in that order so that the less specific selector is second. Give them two different colors. Notice that the more specific selector, even though it is first in the cascade, still overrides the less specific selector.

The principles of creating selectors that I've just discussed should help you really lighten up your CSS documents. For more examples of writing efficient CSS, see John Gallant and Holly Bergevin's free article, Writing Efficient CSS, at Community M (www.communitymx.com/abstract.cfm?cid=90F55). Now let's move on to a real world example of the power of descendant selectors - a site map.

Creating a Site Map Using Descendant Selectors
I've found that descendant selectors can be a simple and elegant solution for creating a site map. Using nested unordered lists and descendant selectors, you can make a very structured, easy-to-read map of any site under your control - no matter how complex. Your visitors will thank you for the nice hierarchal picture. And you'll be happy with the lack of having to class, or style inline, the whole hierarchical mess in your X/HTML document. It's all in the CSS, baby.

First, we'll take a look at the code (if you're working along with he example files this code is in the sitemap.htm file). This example uses three site sublevels. It can be used with as many levels as you need. Simply nest an unordered list for each one (see Code II).

Notice that Code II simply has three levels of nested unordered lists. And also notice that all the lists in the main content area are links (as any self-respecting site map would be). I've included an unordered list in the #side div as well so that you can see how handy more specific descendant selectors can be.

Now let's visualize the document tree for the above code (see Image II).

It's pretty straightforward, isn't it? You can see the way one list descends from the next. Now let's look at what we can do with the CSS. I'm going to keep the properties in the selectors pretty simple here. But play around in your own CSS document using background images and custom bullets. You can get some interesting looks. (If at any time in the following portion of the exercise you get confused by the descendant selectors, avail yourself of the SelectORacle - gallery.theopalgroup.com/selectoracle/ - he knows all.)

We'll leave the basic selectors from the previous page (only removing the two unnecessary descendant selectors - #content p strong and #content ul strong) and continue adding on to our CSS. Visually, what I want to do with the site map is alternate between a square and a circle bullet. I also want the bullets to be orange, but I want links to start with a brighter blue and, at each level, move to a darker hue. It's just a simple visual cue, in addition to the natural indentation, to let people visualize the difference between the levels. Last, I'll remove the underlines on the links but have them roll over to orange with underlines. Let's get started.

The first thing I want to establish is that all ul on my page should be orange. Remember, this will style all ul, not just the ones in the #content div. Something to remember about lists that contain links - like in the case of site maps - even though you'll give the links their own color, the bullet itself will be the color you've given to the list, not the link. Remember, the link is contained in the list. Since I want my bullet to be the complementary orange to the link's blues, I assign that to the ul:


ul {
	color: #C30;
}

Now I'll remove all the underlines from the links using a descendant selector. This one will take care of all the lists no matter how nested they are. Descendants do not care how far down the document tree they are. They just know that they descend and thus they obey (if only our children were that way):


ul a {
	text-decoration: none;
}

In order to have every other level alternate the square bullets with the round ones, I'm going to group selectors. If you haven't tried it, grouping is yet another way to cut down on your CSS document weight. If you have selectors with identical properties, simply place one after the next separated by a comma and a space (the space is imperative for it to work properly). Let's look at an example:


ul li, ul ul ul li {
	list-style: square;
}

Notice that we gave only the list items from the first- and third-level unordered lists the square list style. Let's give the second level lists a round disc style:


ul ul li {
	list-style: disc;
}

Next, we need to give each level its own link color as I described previously. I'm also going to give the primary level a heavier, bold styling. This means I've got to set any lists that follow back to their normal weight (see Code III).

As we discussed, descendants don't care where they come in the document tree. So once we changed the font weight back to normal, the next level follows suit. Last, we need to set the hover, active, and focus styles of our links (for further information about the accessibility reasons for these link styles as well as more information about descendants and styling and positioning with CSS, see my tutorial at Community MX - From Design to Completion: Case Study One - www.communitymx.com/abstract.cfm?cid=A5BE27AD9A15909B). Since I want all the rollover styles to be the same, I have to set them only once:


ul li a:hover, ul li a:active, ul li a:focus {
	color: #C30;
	text-decoration: underline;
}

Save and upload the page. You should have three levels of blue links with orange bullets. The side bar list should be orange. The side bar list could be styled as buttons if you wish, using descendant selectors that begin with #side. There would be no conflict. See how powerful it is? In this example, the only extra information stored in the actual X/HTML portion of the document is two little IDs. Not a single class was harmed in the writing of this article. As always, go forth and style!

About Stephanie Sullivan
Stephanie Sullivan is a Web developer, partner at CommunityMX (www.communitymx.com), owner of VioletSky Design (www.violetsky.net), and contributing author of Dreamweaver MX 2004 Magic.

In order to post a comment you need to be registered and logged in.

Register | Sign-in

Reader Feedback: Page 1 of 1

Latest Cloud Developer Stories
CloudBench Applications, Inc. announced its financial results for the three months and nine months ending September 30, 2009. All amounts are stated in Canadian dollars unless otherwise noted. Revenues from BasicGov, the Company's cloud computing solution for local government, gr...
The new contract is an industry first, with CSC being the first Microsoft partner to lead and win a cloud computing services agreement of this scale. Under terms of the contract, CSC will provide Royal Mail Group's 30,000 employees with access to new IT services using Microsoft's...
Operates in over 170 countries and is one of the world’s leading providers of communications solutions and services. Richard Tarboton talks for MeettheBoss.TV on his role as Head of Energy & Carbon for BT and what they are doing towards reducing carbon emissions.
CA is going to put its Agile Planner software on salesforce.com’s Force.com platform in the first half to accelerate development time and give users visibility over their development initiatives to reduce time-to-market. Customers are supposed to be able to accelerate the deploym...
Despite its uncertain fate Sun soldiers on. Monday it trotted out a cloud-based multiplatform desktop as a service for K-12 and community colleges that can run Windows, the Mac OS, Linux and Solaris applications to nearly any client device, including its own Sun Ray thin clients....
Subscribe to the World's Most Powerful Newsletters
Subscribe to Our Rss Feeds & Get Your SYS-CON News Live!
Click to Add our RSS Feeds to the Service of Your Choice:
Google Reader or Homepage Add to My Yahoo! Subscribe with Bloglines Subscribe in NewsGator Online
myFeedster Add to My AOL Subscribe in Rojo Add 'Hugg' to Newsburst from CNET News.com Kinja Digest View Additional SYS-CON Feeds
Publish Your Article! Please send it to editorial(at)sys-con.com!

Advertise on this site! Contact advertising(at)sys-con.com! 201 802-3021

SYS-CON Featured Whitepapers
ADS BY GOOGLE

Breaking Cloud Computing News
CloudBench Applications, Inc. announced its financial results for the three months and nine months e...