If you're new here, you may want to subscribe to my RSS feed. So that you can read the latest updates about Web2.0 tools, Making Money Online, Tips in SEO, Ajax and many more. Thanks for visiting ProgramimiCOM!
The oldest usability guideline for any type of navigational design is to help users understand where they’ve been, where they are, and where they can go (past, present, and future). The three are somewhat interrelated: a good grasp of past navigation helps you understand your current location, since it’s the culmination of your journey. Knowing your past and present locations in turn makes it easier to decide where to go next.
On the Web, links are a key factor in this navigation process. Users can exclude links that proved fruitless in their earlier visits. Conversely, they might revisit links they found helpful in the past.
Most important, knowing which pages they’ve already visited frees users from unintentionally revisiting the same pages over and over again.
Generally, Web browsers are severely deficient in supporting user navigation. However, they do provide one feature that helps users orient themselves: browsers let designers display links in different colors, depending on whether the links lead to new pages or pages that users have seen before. Changing the color of visited links has been part of Web browsing since Mosaic arrived in 1993, so it’s completely standard; almost all users understand it. Currently, 74% of websites use different colors for visited and unvisited links, making this design approach a strong convention that people have come to expect.
Hypertext theory, the Web’s history, and current design conventions all indicate the need to change the color of visited links. Further, empirical observations from user testing have identified several severe usability problems on sites that violate this convention. When sites use the same color for visited and unvisited links, users:
Such usability problems are particularly damaging to users with weak short-term memory, who often have trouble remembering what they’ve clicked without a visual representation. Of course, “weak short-term memory” is an inherent shortcoming of all humans, which is why all users are harmed by unchanging link colors. But this definitely impacts some people more than others, so it’s particularly important to change link colors if you have many older users.Given the extensive theoretical and empirical support for using different link colors, it’s astounding that a quarter of all websites continues to inflict extra usability problems on people by choosing a uniform link color.
Even people who believe in usability sometimes question the need for changing link colors. I think this is because they don’t pick up on the problems caused by unchanging links when they conduct their own user testing. Unfortunately, the symptoms of these problems are among the most difficult to detect when you observe users. User testing is basically easy: we teach it in three days. Most important usability problems are so glaring that anybody can identify them through a simple test. Once you know the basics of how to write good tasks and how to facilitate the session without biasing user behavior, you can clearly see users get into trouble when they encounter poorly designed components of your site.
Say, for example, that a user clicks the wrong button. It’s obvious to any observer that such behavior represents a design error. Listening to users’ comments prior to clicking usually tells you why they misunderstood the design, thus guiding you to make it better in the redesign.
Cases in which users don’t do something are harder to discover. Even so, most usability facilitators can identify many such problems. You might, for example, observe that no one in your test clicked on one of your major features. Users’ thinking-aloud comments will make it clear whether they (a) saw the feature, but didn’t find it relevant; or (b) never considered the feature because it looked too much like an advertisement.
Some usability problems require more detective work and are often overlooked by people relatively new to user testing. This is particularly true for problems that are a composite of multiple individual issues scattered around the site. Identifying these problems is even more difficult when none of the individual issues cause difficulties on their own. A relatively simple example of a multi-location problem is when a homepage link sets certain expectations that cause users to misinterpret the information on the destination page. The link text itself might be clear, and users are unlikely to complain about it. The destination page might also be clear, and users might not complain about it, either, because they think they understand it. The problem is that they understand it wrong because they interpret it in the context of their misguided expectations. This type of usability problem requires test observers to make high-level conclusions based on remembering what happened on the previous page, even though nothing that happened seemed to cause users difficulties.
The damage that unchanging link colors cause is one of the most tricky usability problems to identify in user testing. On any given page, users seem to understand the links just fine. Users almost never complain about link colors, as long as they’re distinct from the rest of the text and reasonably legible. Life is good, or so it seems.
Observe carefully, though, and you’ll notice that users frequently move in circles. They’ll visit the same page multiple times — not because they want to, but because they don’t realize that they’ve already been there. Users will give up when they’ve tried most links in a list, even though there’s one link that they haven’t tried; if the links don’t change colors, users don’t realize that there’s only one unvisited link remaining.
Unchanging link colors also create navigational confusion because users don’t quite understand their different choices or where they are. Of course, this problem could also be a symptom of muddled information architecture or poorly written labels, which is why it requires experience to identify the true root cause of the users’ difficulties.
Even though the downsides of unchanging link colors are easily overlooked in user testing, they’re very real and problematic for users. Many other design strategies for helping users navigate, such as site maps, require a good deal of work. But the browser lets you change link colors for free, so there’s no reason not to take advantage of this simple way to help your users.
Using different colors for visited and unvisited links makes your site easier to navigate and thus increases user satisfaction.
21 Jul
Posted by ProCOM
on July 21, 2007 – 9:06 pm - 1,141 views
If you’d rather not muck with the innards of your httpd.conf file, there’s a sensible and less overwhelming alternative solution, at least if you’re using the Apache web server. Instead, create a file in your Web site’s home directory called .htaccess (yes, that’s a dot or period as the first letter. It’s very important!)
You can accomplish this if you have direct edit capabilities on your server, or you can create a file with the correct name on your PC or Macintosh and upload it to the server. Regardless, the content of the file should be exactly:
ErrorDocument 404 /404-error-page.html
In this instance, you’re defining the name of your error page to be exactly 404-error-page.html and that it’s going to live at the topmost directory of your Web site. If you’d prefer a different name, then modify the contents of this file appropriately.
If you use FTP to upload this file to your server, make sure that you transfer it in “text” or “ascii” mode so that it’s properly parsed by the server.
There are lots of different error 404 pages you can create, ranging from the succinct and dry to the peculiar, to the witty, to the super-helpful (for example, you can easily add a google search for only pages from your site to your 404 error page ).
Whichever path you choose, you’ll find people appreciate if you at least offer a link to your home page and some method whereby they can contact you if they are insistent that certain material should be present but isn’t.
Also, most people agree that not insulting them is a good strategy, but, perhaps surprisingly, this varies and there are definitely some 404 error pages out there that are quite blunt.
It depends on the style of your site, your sense of humor, and whether you want to err on the side of “useful” or on the side of “amusing”.
To get the change to the configuration file accepted, you’ll probably need to restart or otherwise nudge your Apache Web server so it knows that you’ve added a custom 404 error page (otherwise it’ll continue to blithly serve up the generic error page instead).
There are a couple of basic commands to accomplish this task:
Regardless of which you choose, it’s always a good idea to also check the log files for the Web server to ensure that everything was accepted and parsed without any errors. On a typical Linux/Unix configuration, the log file would be at
/var/log/messages
because Apache (almost always) is configured to use the standard syslog mechanism.
Once that happens, type in a URL that you know isn’t present on your site and see what happens! If everything is correct, you should see the new 404 error page pop up.
If it doesn’t work, go back to your httpd.conf file, identify where errors are logged (probably an entry ErrorLog) then look in that file to see what’s wrong.
Most likely you have a naming error where it’s called one thing in the configuration file but something else on the actual server.
If everything is working fine, try a second 404 error by requesting a page that’s a few subdirectories into the site, so while for your first test you may have used something like http://www.example.com/badpage this time try something more like http://www.example.com/some/subdir/badpage
If all the graphics are displayed properly and the links to elsewhere on your site are all correct, congratulations! You’ve done it! You’re now the proud owner of a custom 404 error page.
If not, step through this tutorial again, keeping an eye on the error log file, and you should have this figured out in no time.
Textual links should be colored and underlined to achieve the best perceived affordance of clickability, though there are a few exceptions to these guidelines. Here are the current usability guidelines for showing textual links:
These guidelines all relate to the textual link appearance. It’s even more important that you carefully choose the link content (the actual words), but that’s another topic. Graphical links are yet another story, but it’s usually best to use text for most links anyway. Following the usability guidelines for link appearance on your site will make it easier for users to immediately determine what they can do on each page and will reduce the probability that they’ll overlook important links.
PDF is great for one thing and one thing only: printing documents. Paper is superior to computer screens in many ways, and users often prefer to print documents that are too long to easily read online.
For online reading, however, PDF is the monster from the Black Lagoon. It puts its clammy hands all over people with a cruel grip that doesn’t let go.
The usability problems that PDF files cause on websites or intranets are legion:
In several recent usability studies, users complained woefully whenever they encountered PDF files. Following are quotes from investors testing the investor relations area on corporate websites:
“It’s a pain that I have to download each PDF. Pain in the ass… I find it to be annoying. It’s slow to load. It’s hard to search within it. I find HTML easier to deal with… This is all PDF instead of a chart. My dream site is to come to a site and get a bar chart for the sales within the last ten years.”
“I hate Adobe Acrobat. If I bring up PDF, I can’t take a section and copy it and move it to Word. There could be stuff like graphics I don’t want. I prefer documents in HTML format so that it’s editable.”
The following user quotes are from journalists testing the PR area on corporate websites:
“They [PDF files] don’t behave like Web pages. It’s not the speed. It is like having a solid thing rather than a fluid thing.”
“What we’ve got is a page of a PDF document which is great when printed out, but on the screen it is hard to read. The print is too small…”
“I am a little frustrated with Acrobat… They made every page a file. So what happens here is when you scroll, it jumps, which is really not helpful.”
This quote is from an employee who was testing an intranet:
“It would have helped if the first page was an index and you could scroll to it. That must be what this side part means. But who am I to say?”
As the last quote shows, even when a PDF file has its own navigation aides, they don’t typically help because they’re nonstandard and based on a paper metaphor rather than hypertext navigation.
We’ve had similar reactions from users in many other studies, including tests of B2B websites where users complained when sites presented product specs or customer success stories in PDF instead of Web pages. Here’s a quote from a customer who shunned those parts of the site that were in PDF:
“It looks like I’m going to have to go to PDF, which I’m dreading.”
Users love search for two reasons:
Search is a big deal: the usability of the search on intranets we have tested accounted for 43% of the difference in employee productivity between intranets with high and low usability.
Users often move fast and furiously when they’re looking for search. As we’ve seen in recent studies, they typically scan the home page looking for “the little box where I can type.” We’ve long known that users scan, and the implications are clear:
When I changed the useit.com home page to include a search box instead of a link, search engine use increased by 91%. Small change, big effect (as is often the outcome when implementing usability guidelines). (Interior pages may use a search link if they have a very simple design; complex interior pages should use a search box.)
Given that search is becoming old hat on the Internet, you might think users would develop advanced search skills. Not so. Typical users are very poor at query reformulation: If they don’t get good results on the first try, later search attempts rarely succeed. In fact, they often give up. We recently studied a large group of people as they shopped on various e-commerce sites. Their search success rate was:
| First query: | 51% |
| Second query: | 32% |
| Third query: | 18% |
In other words, if users don’t find the result with their first query, they are progressively less and less likely to succeed with additional searches. Many users don’t even bother: In our study, almost half the users whose first search failed gave up immediately.
There is no question that we need to develop methods to help users hone their searches. Probably the only long-term solution is for the school systems to teach kids strategies for query reformulation. In the short term, search interfaces could show users easy ways to extend queries.
Realistically, though, search design should assume that most users won’t be willing or able to refine their queries. Given this, the emphasis should be on increasing users’ success on the first attempt.
Another reason to emphasize early success is that users typically make very quick judgments about a website’s value based on the quality of one or two sets of search results. If the list looks like junk, they may abandon the site completely. At a minimum, they’ll forgo the site’s search in favor of external search engines like Google.
In our recent search study, the mean query length was 2.0 words. Other studies also show a preponderance of simple searches. Most users cannot use advanced search or Boolean query syntax. This has two implications for search design:
Scoped search lets users limit the search to results from specific areas of the site (the search scope). In general, this is dangerous. Users often overlook the scope, or they think they are in a different site area than the one they are actually searching.However, as websites continue to grow and offer multiple services in a single site, my attitude toward scoped search is changing. I now believe scoping can be sufficiently useful if you offer it in areas of the site that are both clearly delimitated and address specific problems.
If you choose to use scoped search, I recommend following a few basic rules:
Users almost never look beyond the second page of search results. It is thus essential that your search prioritize results in a useful way and that all the most important hits appear on the first page.Also, look through the most common queries in your search engine logs and determine the optimal landing page for each common query. You can then manually tweak the search engine to show these pages as the #1 hit.
The Internet enriches many seniors’ lives, but most websites violate usability guidelines, making the sites difficult for seniors to use. Current websites are twice as hard to use for seniors than for non-seniors.Seniors are one of the fastest growing demographics on the Web. The United States alone has an estimated 9 million Internet users over the age of 65 as of September 2004. Indeed, all industrialized countries have huge populations of senior citizens, many of whom have substantial assets. Although they are typically retired, seniors lead very active lives and often have great interest in modern technologies such as the Internet, which gives them another method to communicate and stay informed.
In our study, email was the main Internet application used by seniors. Our participants used the Web mainly for:
Indeed, our study participants used the Web to read about and research a wide variety of hobbies and special interests, ranging from genealogy to cooking, war strategy, and musical instruments. Taken together, reading about such hobbies constituted a major use of the Web: The diversity of specialized sites is just as much a killer app for seniors as it is for other users.
To learn how seniors use the Web, we conducted three series of usability tests:
We define “seniors” as people over the age of 65. Most of our test users were in their 70s, but we also included some people who were 80 years or older, and several people between 65 and 69.
In the quantitative study, we asked users in both groups to perform the same four tasks:
The following table shows the measurements of four usability attributes averaged across the four tasks.
| Seniors (65+ Years) |
Control Group (21-55) |
|
|---|---|---|
| Success Rate (task completed correctly) | 52.9% | 78.2% |
| Time on Task (min:sec) | 12:33 | 7:14 |
| Errors (erroneous actions per task) | 4.6 | 0.6 |
| Subjective Rating (scale: 1=low, 7=high) | 3.7 | 4.6 |
| Overall Usability (normalized geo. mean) | 100% | 222% |
The differences between seniors and the control group are all highly significant.
Normalizing the usability metrics so that the seniors’ scores are the baseline value of 100% in all cases leads to an estimated overall usability of 222% for non-seniors. (Averaging computed as the geometric mean.) In other words, overall usability was slightly more than twice as good for non-seniors as it was for seniors.
Websites tend to be produced by young designers, who often assume that all users have perfect vision and motor control, and know everything about the Web. These assumptions rarely hold, even when the users are not seniors. However, as indicated by our usability metrics, seniors are hurt more by usability problems than younger users. Among the obvious physical attributes often affected by the human aging process are eyesight, precision of movement, and memory. Also, many seniors retired without having used computers and the Internet extensively during their working careers. Thus, they have not necessarily learned good conceptual models of how these technologies work, which makes it more difficult to understand their quirks. For example, we observed several users who did not differentiate clearly between a website’s search box and the browser’s URL box. After all, both are input fields that you type in when you want to go elsewhere. The lack of experience with good conceptual models is obviously not fundamental to human biology, and may disappear as the current workforce retires.
Our testing identified many instances of poor design that compounded to make the Web more than twice as hard for seniors to use. Complying with the guidelines for designing for seniors would remove many such usability problems. And, while Web usability might still be slightly better for younger users, the differences could be reduced drastically.
The most widely known principle for supporting seniors’ computer use is to support larger font sizes than those younger users prefer. The principle may be well known, and it was indeed confirmed by our study, but still, it is frequently violated by sites that freeze text at a tiny font size. Sites that target seniors should use at least 12-point type as the default. And all sites, whether or not they specifically target seniors, should let users increase text size as desired — especially if the site opts for a smaller default font size.
For hypertext links, large text is especially important for two main reasons: 1) to ensure readability of these essential design components, and 2) to make them more prominent targets for clicking. You should also avoid tightly clustered links that are not separated by white space. Doing so will decrease erroneous clicks and increase the speed at which users hit the correct link. This rule also applies to command buttons and other interaction objects, all of which need to be reasonably large to be easy to click.
Pull-down menus, hierarchically walking menus, and other moving interface elements cause problems for seniors who are not always steady with the mouse. Better to use static user interface widgets and designs that do not require pixel-perfect pointing.
When websites violate the guideline to use different colors to clearly distinguish between visited and unvisited links, seniors easily lose track of where they have been. We’ve certainly seen the same problem among all age groups: It’s confusing when websites change the standard link colors, and it’s particularly confusing when the same color is used for all links, whether or not you have visited the destination page. However, seniors have a harder time remembering which parts of a website they have visited before, so they are more likely to waste time repeatedly returning to the same place. Seniors also have a harder time using unforgiving search engines and forms. We saw users thwarted because they typed hyphens in their search queries, and punished because they used hyphens or parentheses in a telephone or credit card number.
Error messages were often hard to read, either because the wording was obscure or imprecise, or the message’s placement on the page was easily overlooked among a profusion of other design elements. Simplicity is even more important than usual when seniors encounter error handling: Your message should focus on the error, explain it clearly, and make it as easy as possible to fix. Also, as much as possible, website tasks should adapt to seniors and their preferred way of doing things. After decades of writing telephone numbers in a certain way, it’s not a very nice experience to come across a form that insists on a different format.
Seniors strongly prefer those websites that are easiest for them to use. The correlation between the success score for our test tasks and users’ subsequent subjective rating of the sites was very strong: r = 0.78, which is higher than we have found in most other studies, though not as high as the 0.95 we found in our equivalent study of users with disabilities. Usability for seniors is important, and not just so that they can perform a task aimed at a one-time purchase. By focusing on improving usability for seniors, you can increase their satisfaction and the odds of forming a long-term relationship.
Intranets should also cater to seniors. Most companies have employees in their 60s, and many big companies have special extranets for retirees that provide online benefits information and help the company maintain contact with former employees.
Besides the business reasoning, we all have a very personal interest in increasing usability for seniors: It’s the one user category we’re all likely to join one day.
When it works for them, the Internet is already an enriching part of many seniors’ lives. Websites can become much more approachable, however, by following the simple design guidelines in our new report. If you consider these guidelines from the start, implementing them will rarely add to the cost of a Web design or intranet project. Also, many of the guidelines for increasing usability for seniors help other users as well.
21 Jul
Posted by ProCOM
on July 21, 2007 – 8:18 pm - 384 views
Ole Begemann writes:
While I agree with your assessment, I wonder how AJAX fits into this. AJAX is all about interactivity within the same page. Do you think this does more harm than good because of the confusion it causes (and e.g. the Back button does not work as expected anymore)? Or should AJAX actions be invoked by buttons rather than links?
Jakob’s answer:
Interactivity (i.e., features) and navigation are different. So it should be OK to have things happen within the same page as long as they are not seen by users as representing a movement to a new location. See this screenshot for an example:
Screenshot of the price of a stock over three months from Yahoo! Finance.
This is a stock chart showing the price of Amazon.com’s stock over three months. Click the link marked “1y” to get the price over a year instead. It so happens that the implementation is a link to a new page, instead of a within-page refresh-in-place, but there’s no reason for that, except for the benefit I get from being able to easily copy the URL and link to it in the caption. Anyway, if Yahoo had used a button instead of a link to change the view of that chart, it should have worked well as a within-page refresh.Most likely it should be a guideline to use a different UI widget than a plain-text link for this purpose. For sure, we know that it’s a guideline to use buttons for commands and links for navigation, and changing the view of a chart seems more like a command than it seems like navigation. An alternative, in the example in the screenshot, would be to use tabs to alternate between the views. This would certainly comply with the standard use of tabs in applications, even though there would be a conflict with the way tabs have often been abused on websites (which often use tabs to denote navigation instead of alternate views).
For switching between alternate views of the same data, it’s actually better if the Back button doesn’t work, because it would mainly be used when the user wanted to return to the previous location (say, the list of stocks they’re tracking), not if they want to see the previous data view again.
The operative question is whether the user’s action feels more like a manipulation of the same data or a movement to some new data. If the former, then it’s a command. If the latter, it’s navigation. To really find out, you need to observe users and perform a task analysis, but often you can come up with a good first guess and use for your initial design before it goes to testing.
Vincent Simard writes:
Should “Return to top” links be avoided? They seem accepted by a lot of developers and users although I have not tested them vs. users scrolling back to the top of a page manually.
Jakob’s answer:
Yes, “return to top” can be avoided, because the exact same functionality is provided by simply dragging the scrollbar to the top of the page. It’s almost always better to rely on a single, generic interaction technique so that users don’t have to ponder the choice between two alternate interaction techniques for the same goal. The time it takes to make the decision is usually more than the time saved by the shortcut. (The exception would be for extremely long pages that would take forever to scroll, but such pages should be avoided in the first place.)
J. D. A. Wiseman writes: Internal links are not only for long lists: also wide maps that cannot be less wide.
Jakob’s answer:
Of course, in general, there’s a guideline to avoid horizontal scrolling, but a wide map would be one of the exceptions. For a low-tech solution, within-page links may be an acceptable way to jump to a specific part of this type of map. A more fancy solution would be to have a special map controller, but that would be overkill for a simple site like yours.
Mike Elledge writes:
I would suggest another situation where skip links are both a benefit and meet user expectations: When used to skip navigation (or, alternatively, go to content) for persons using adaptive technology.
This is commonly recommended by persons within the accessibility community to enable AT users to avoid unnecessary tabbing, reducing fatigue and repetition. Screen readers, such as JAWS, identify such links as “in-page” so that users are further informed.
Jakob’s answer:
This is a good point, and may be one of the few cases where the user experience is better for users with disabilities than for non-disabled users. In general, our testing has found that blind and low-vision users suffer three times as bad usability problems as sighted users, so it’s only fair that they get one thing in their favor. When you use a browser that gives special (and appropriate) treatment to within-page links, then they can certainly be helpful. The most common use of “skip links” is a link on the top of the page that moves users directly to the content area of the page, thus bypassing the extensive amount of crud in the form of navigation bars and other utility information. Sighted readers almost always skip this information initially, simply by looking in the content area first. Non-sighted users sometimes (but not always) like to start with the content as well, and skip-links is one way to give them this choice.
A skip-link is usually made invisible to sighted users, and thus it won’t bother people with traditional, visual browsers.
In the long run, I believe that a better solution would be to have a semantic encoding that would denote different parts of a page as content vs. navigation and include a dedicated command in screen reader software for switching between the two. These two different areas of a page need to be accessed in different task modes, and it’s almost as common to need to move from content to navigation as the other way around.
Some specialists in technical accessibility (which is a different discipline than usability for users with disabilities) suggest an alternative: place the content first and the navigation second in the file and then use CSS to reverse this order for sighted users. This is not a good idea:
I thought I’d share a little bit of what I’ve learned from noodling around with stylesheets these past few years. Here are some basic organizational practices I try to follow. ( Much of this might be old hat for you, and if so, just think of it as a refresher. I run into enough messy stylesheets that I thought this might be of some interest. )
Group your styles into categories (ex. layout, typography, forms, so on) and visually seperate them in your css file. A title and table of contents doesn’t hurt either:
/*
HuddleTogether.com Screen Styles
Table of Contents:
layout
typography
forms
*/
/* layout
----------------------------------------------- */
/* typography
----------------------------------------------- */
/* forms
----------------------------------------------- */
Even though I do have some common practices, I don’t have a ‘template’ for how to breakdown styles into categories.
For starters, I almost always have layout and typography categories. With typography defining the sitewide look and feel. Depending on the complexity, I may break out the table and form styles into their own categories.
Next, I address the physical sections of the page with their own categories: header, sidebar, content, and footer for example. Lastly, I collect the page and content section specific styles and place them in their own category (and sometimes subcategories).
Another method is to categorize the styles and place them in seperate CSS files which are all imported by one main CSS file. I find this method good in theory but it can lead to overlapping styles, specification issues, and general confusion if you’re not very careful:
@import url("layout.css");
@import url("typography.css");
@import url("forms.css");
When styling multiple tags, ids, or classes with common attributes, display each on its own line. Also, indent closing braces. Both these actions keep the left column clean so you can quickly skim your stylesheet:
h2,
h3,
h4 {
font-weight: bold;
padding-bottom: 1.5em;
}
h5 {
font-weight: normal;
font-size: 1.5em;
padding-bottom: 0;
}
Use descendant selectors generously and consistently to keep your styles grouped neatly and CSS specificity in check:
#header {}
#header .logo {}
#header .logo img {}
A trick I use all the time to temporarily disable a style attribute involves simply adding an ‘x’ in front of the attribute name. It’s safer then cutting and quicker then commenting out:
#footer{
border-top: 1px solid #e5e5e5;
xborder-bottom: 1px solid #e5e5e5;
}
Quick HTML pointer. For div tags that stay open for a number of lines, add a small comment after the closing tag about the opening div’s id or class:
<div id="content">
<h2></h2>
<p></p>
<p></p>
<p></p>
<p></p>
</div><!-- end #content-->
A few weeks back in Cupertino, I saw Aaron explain how the specificity of CSS selectors is calculated in a way which I hadn’t seen before. Then today I came across a knotty problem while building XHTML and CSS templates for a new project where two selectors behaved differently to how I expected and I realised that I had not completed my training.
My problem was a simple one, how to feed a transparent PNG image to browsers which support transparency and a GIF image to older browsers which don’t, without resorting to hacks. Here’s the markup,
<div id="nav-supp"> <p><a id=”a-02″ href=”#webstandards-org”>Top</a></p> <!– etc. –> </div>
and my CSS starting point.
a#a-02 { background-image : url(n.gif); }
a[id="a-02"] { background-image : url(n.png); }
I had assumed that a modern browser would see and apply both rules (with the second overriding the first) and that an older browser which does not understand attribute selectors would see and apply only the first, ignoring the second. I was wrong. Modern browsers did not apply the PNG image as I expected. The reason? A standard id selector wins over an attribute selector in terms of the cascade. Dagnammit! I know I should have read the specs, but somehow that particular pleasure had escaped me. If I had, I might have learned that;
ID selectors have a higher specificity than attribute selectors. For example, in HTML, the selector #p123 is more specific than [id=p123] in terms of the cascade.
A little Googling uncovered some rather dry reading on the subject of selector specificity (resources below).
First, let’s look back at the subject of specificity (with one or two minor changes to fit our nefarious purpose).
You give every id selector (”#whatever”) a value of 100, every class selector (”.whatever”) a value of 10 and every HTML selector (”whatever”) a value of 1. Then you add them all up and hey presto, you have the specificity value.
phas a specificity of 1 (1 HTML selector)div phas a specificity of 2 (2 HTML selectors; 1+1).sithhas a specificity of 10 (1 class selector)div p.sithhas a specificity of 12 (2 HTML selectors and a class selector; 1+1+10)#sithhas a specificity of 100 (1 id selector)body #darkside .sith phas a specificity of 112 (HTML selector, id selector, class selector, HTML selector; 1+100+10+1)If all of these examples were used,
div p.sith(with a specificity of 12) would win out overdiv p(with a specificity of 2) andbody #darkside .sith pwould win out over all of them, regardless of the order.
Darth (Gez) Lemon quotes the W3C.
A selector’s specificity is calculated as follows:
- count the number of
IDattributes in the selector (= a)- count the number of other attributes and pseudo-classes in the selector (= b)
- count the number of element names in the selector (= c)
- ignore pseudo-elements.
Concatenating the three numbers a-b-c (in a number system with a large base) gives the specificity.
Too much! For me, the W3C really is in a galaxy far, far away!
Math was never my strong point, so to help me understand calculating specificity better I made a chart based on the following specificity (or Sith power) values (Ed says: Ignoring inline styles
and !important).
element selector class selector id selector
Sith power (specificity): Sith power (specificity): Sith power (specificity):
0,0,1 (1) 0,1,0 (10) 1,0,0 (100)
Each character (selector) is given its own Sith power (specificity value) depending on how powerful they are in the ways of the Dark Side. A storm trooper is less powerful than Vader who is in turn less powerful than the Emperor.
Amazingly, Star Wars helped me understand CSS better. Join me, and together we can rule the galaxy as father and geeks!
Any thoughts? (Ed says: Cue Star Wars quotes ;)
)
If you have two (or more) conflicting CSS rules that point to the same element, there are some basic rules that a browser follows to determine which one is most specific and therefore wins out.It may not seem like something that important, and in most cases you won’t come across any conflicts at all, but the larger and more complex your CSS files become, or the more CSS files you start to juggle with, the greater likelihood there is of conflicts turning up.
If the selectors are the same then the latest one will always take precedence. For example, if you had:
p { color: red; }
p { color: blue; }
p elements would be coloured blue because that rule came last.
However, you won’t usually have identical selectors with conflicting declarations on purpose (because there’s not much point). Conflicts quite legitimately come up, however, when you have nested selectors. In the following example:
div p { color: red; }
p { color: blue; }
It might seem that p elements within a div element would be coloured blue, seeing as a rule to colour p elements blue comes last, but they would actually be coloured red due to the specificity of the first selector. Basically, the more specific a selector, the more preference it will be given when it comes to conflicting styles.The actual specificity of a group of nested selectors takes some calculating. Basically, you give every id selector (”#whatever”) a value of 100, every class selector (”.whatever”) a value of 10 and every HTML selector (”whatever”) a value of 1. Then you add them all up and hey presto, you have the specificity value.
p has a specificity of 1 (1 HTML selector)div p has a specificity of 2 (2 HTML selectors; 1+1).tree has a specificity of 10 (1 class selector)div p.tree has a specificity of 12 (2 HTML selectors and a class selector; 1+1+10)#baobab has a specificity of 100 (1 id selector)body #content .alternative p has a specificity of 112 (HTML selector, id selector, class selector, HTML selector; 1+100+10+1)So if all of these examples were used, div p.tree (with a specificity of 12) would win out over div p (with a specificity of 2) and body #content .alternative p would win out over all of them, regardless of the order.