IDs are anchors, too.

by Bill Brown on Monday, September 14, 2009 39 Responses

While browsing the internet these days, I see a lot of this:

<body>
...
<a name="top"></a>
...
<a href="#top">- Back to Top -</a>
...
</body>

There’s an easier, better and prettier way. CSS Signatures are all the rage these days. If you’re not familiar with a CSS Signature, it’s basically nothing more than an ID on your body tag, like this:

<body id="www-domain-tld">

The fundamental purpose of the CSS Signature is to allow a user to specify style adjustments to your site in their own user style sheets. Whether or not users are actually capitalizing on this is a discussion for another day, but doing this has other benefits like having an extra id to use when dealing with CSS specificity.

Additionally, we can use this to capitalize on a little known fact about HTML and anchors: you can use anchors to jump to any element on your page with an ID attribute.

Let me repeat that: You can jump to any element with an ID attribute on any page.

Here’s an example, if you don’t believe me: Nowhere on CNN.com’s homepage will you find a link to their footer, and you’ll find no mention of <a name="cnnFooter"></a> in the code but if you follow this link to CNN you will in fact find yourself staring at the footer on the CNN homepage. This is because their footer div has “cnnFooter”cnn_ftrcntnt” as the ID which allows me to jump directly to that element.

Oh sure, I know what you’re thinking: “Great, so how do I get this to work in IE?” Surprise: it works just fine in IE, at least as far back as IE 5.5 and maybe further. So, here we have a nice, tidy little tidbit with no cross-browser issues.

So, we can do away with the empty anchor element at the top of our pages and instead do this:

<body id="www-domain-tld">
...
<p><a href="#www-domain-tld">- Back to Top -</a></p>
...
</body>

Trying to be all kinds of accessible with the “Jump to Content” link? Try this:

<p>
	<a href="#content">- Jump to Content -</a>
</p>
...
<div id="content">
	<p>Neat, huh?</p>
</div>

Also works well on comments:

<p>
  <strong>Update:</strong>
  Based on <a href="#comment-12345">so and so's comment</a>...
</p>
...
<blockquote id="comment-12345">
  <h3>On Day X, so and so said:</h3>
  <p>Blah blah blah...</p>
</blockquote>

…and comment forms:

<p>
  <strong>2 Responses</strong>
  <a href="#comment-form">- Jump to Comment Form -</a>
</p>
...
<form id="comment-form" method="post" action="">
...
</form>

Using this approach will streamline a lot of your code, allowing you to get rid of a ton of those empty anchor elements. It also allows for greater flexibility when linking to content on other’s sites. Not to mention that using it means you can sit at the cool kid’s table.

About the Author

Over the course of 33 years, Bill Brown has lived and worked in West Africa as a Field Station Coordinator on Bioko Island in Equatorial Guinea, represented the Memorex line of consumer electronics on QVC, owned a squirrel, taught improvisation and stage combat and launched two successful improv comedy troupes. Oh, and along the way, he’s developed some websites and applications.

Self-taught with a penchant for entertaining others, Bill’s clients have included internationally renowned photographer Steve McCurry, The National Maritime Law Enforcement Academy (whose site was developed entirely in the rain forests of Bioko Island), Virtual Giving, Workforce Strategy Center and the WSC web application Pathways to Competitiveness. Bill was also a presenter at the 2008 National Association of Government Webmasters conference in Chicago, IL.

Bill is the creator of WebDevelopedia.com and is an active member of several discussion lists, including the CSS Discussion List. When not online, Bill can be found enjoying the company of his girlfriend, Jessica and their dog, Leica (she doesn’t have a web site).


39 Responses

Add a comment

[ Gravatar Icon ]

Navjot Singh#1

Thanks for the useful tip. Never knew of this one. It definitely helps in cleaning of code as I always kept creating named anchors when I had to use them.

[ Gravatar Icon ]

Jeff Starr#2

Yes, and there are often times when using an actual anchor prevents the page from returning to the actual “top” of the document, even when placed just before the <body> element. I haven’t been able to figure out why this happens on some designs, but using the id attribute always seems to work perfectly.

[ Gravatar Icon ]

Dean K#3

Can someone please elaborate on “CSS Signatures”?

Is it literally changing it to:

<body id="www-domain-tld">

or is it like:

<body id="example.com">

Is there CSS code to accompany it?

[ Gravatar Icon ]

Jeff Starr#4

I think the idea is to make it easy for users to override CSS styles for a particular page or site by simply prefixing existing selectors in their custom stylesheet. For example, if I wanted Eric Meyer’s site to have a bright red background with white font, I could add the following to my browser’s custom stylesheet:

#eric-meyer-com { background: #cc0000; color: #fff; }

The use of the domain name as the “CSS signature” makes it easy modify any styles while keeping things organized in the stylesheet according to domain.

As for the format of the signature itself, your second example is incorrect because periods are invalid characters for CSS selectors. Hyphens are legit, so we use them in place of periods to segment the domain name.

[ Gravatar Icon ]

Vijay Padhariya#5

Greate post dude, Its very very useful, I will now cleanup my code regarding this,

Thanks,
Vijay

[ Gravatar Icon ]

eric#6

I use for the site signature, which then lets me use to apply different styles to different sections of the site (eg. all pages within support have )

[ Gravatar Icon ]

eric#7

/sigh

<html id="www-sitedomain-tld">

and

<body id="support-section">

(where’s the preview option?!?)

[ Gravatar Icon ]

Helen#8

I know what Jeff is talking about in comment #2. In some designs,

<body><a name="top"></a> ...

doesn’t scroll to the very top of the page, because the a-tag is an inline element. Following directly after the body-tag it will be placed by the browser automatically. And if you have positioned or floating divs in the document, it can happen by obscure browser-rules (float and vertical-align) that the a-tag is not placed at the top of the layout though it is at the top of the mark-up. You probably won’t take notice of it, because it is not visible in the layout.

You can then try to position the a-tag absolutely (top=0) via CSS. But Jeff is right: <body><a name="top"></a> ... does not validate because it is an inline element outside a div (body and html are divs too, but that doesn’t matter here) and it is a piece of behaviour-code that does not belong in the mark-up.

But there is a problem: If you are running a website with one single CSS-file enhanced by body-id’s and real cascading (e.g. body#index #page #article #p versus body#subpage #page #article #p), those id’s cannot be called “top”. But smart scrolltop-javascripts are using the common “name=top”. A dilemma. One way could be:

<body id="index" name="top">
Here, “id” is dedicated to CSS, and “name” is dedicated to the scrolltop-javascript (works well without JS).

[ Gravatar Icon ]

Catherine Azzarello#9

Way cool!

And now that I can sit at the cool kids’ table…what’s for lunch?

Thanks for the tip.

[ Gravatar Icon ]

Max Weaver#10

You seem surprised that Anchors can do this. But is there any other use for Anchors? I am not sure what else they can be used for other than jumping to specific areas of a page.

It’s been that way for as long as I can rmemeber, at last since the late 90’s.

By the way, they don’t work on Safari.

Max

[ Gravatar Icon ]

Helen#11

Max, the article is not about the fact that anchors exist. It is about that they are still in use today. I just tried it in Safari. Works great.

[ Gravatar Icon ]

Chris McCorkle#12

Not too shabby. Looks like it’d work well for going back to top… and also the relative location of divs with ids?

[ Gravatar Icon ]

Jeff Starr#13

@Helen: Thanks for the information and insight. This will give me something to refer to the next time I am dealing with unruly anchor behavior. Note that the name attribute is deprecated in XHTML in favor of id. Using name for scrolltop scripts with HTML is a nice workaround when id is reserved for styling. Thanks :)

@Max Weaver: I don’t think anyone is surprised at the idea of anchors, but replacing them with ids for intra-page navigation may not have been realized by the wider design community. And yes, as Helen points out, anchors work fine in Safari, as do ids used as anchors.

@Chris McCorkle: Absolutely. As mentioned in the article, any element that accepts the id attribute can be referenced and used for intra-page navigation. So comments, quotes, forms, divs, and just about anything else that is needed.

[ Gravatar Icon ]

Mark#14

Anchors have another use in our web-oh-two/RIA/ajaxy times. The problem is seen when you change the content of a page dynamically, eg. by use of AJax, and then the user wants to either

i) Book mark the page
and/or
ii) Refresh the page.

In both of these scenarios, on reload, the original, unchanged webpage will be seen.
One solution is to use and manipulate anchors, specifically the URL string to ‘remember’ the dynamically generated content.

The key is the little known or used javascript attribute ‘document.location.hash’ which is read/write access to the URL after the ‘#’ (That’s a HASH, not a Pound - I’m English dammit!).

Here’s a good enough example of it’s use - enjoy!

http://yensdesign.com/2008/11/creating-ajax-websites-based-on-anchor-navigation/

[ Gravatar Icon ]

Mark#15

I didn’t know about CSS signatures - Cool idea I just implemented it on scamdex.com:

(Not that I will ever see anyone using it :’( )

Eric Meyer is my Hero!

[ Gravatar Icon ]

Helen#16

I’ve found a wonderful piece of jQuery that I’ve been using for a while now. Don’t remember the author’s name, sorry! Scrolling smoothly, using “name=top”, so you can set .
Finally, it rewrites the pathname, so the visitor won’t end up with “pagename.html#top#down#left#right”.

$(function(){

       $('a[href*=#]').click(function() {

       if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
              && location.hostname == this.hostname) {

                     var $target = $(this.hash);

                     $target = $target.length && $target || $('[name=' + this.hash.slice(1) +']');

                     if ($target.length) {

                            var targetOffset = $target.offset().top;

                            $('html,body').animate({scrollTop: targetOffset}, 3000);

                            return false;

                     }

              }

       });

});

PS: Replace the 3000 (milliseconds) by another value to chance velocity.

[ Gravatar Icon ]

Jeff Starr#17

@Mark: Thanks for chiming in on this — I am currently dealing with that exact issue on a new site I am working on. The article you posted may be just what the doctor ordered. Looking forward to checking it out. Also, the portion of a URL that proceeds the hash sign is often (although debatable) referred to as a “fragment identifier” — something that I didn’t realize until I began researching the topic.

@Helen: Awesome snippet. I have been using something similar with jQuery but it doesn’t work with the name attribute. Your code looks like it will do the job nicely. Thanks for sharing :)

[ Gravatar Icon ]

Garrett W.#18

Looks like in the last snippet, you forgot to change the <form id="comment-12345" to id="comment-form" ;)

[ Gravatar Icon ]

Jeff Starr#19

Fixed :)

[ Gravatar Icon ]

Helen#20

What I forgot to mention: The anchor-topic now has become relevant to SEO now: Anchor-IDs are used by Google to section your site in areas which will be display in the search results.

http://googlewebmastercentral.blogspot.com/2009/09/using-named-anchors-to-identify.html

If you have a Google-Webmaster-account: Log in. There is information about whether your site can be sectioned by Google.

[ Gravatar Icon ]

Jeff Starr#21

Awesome tips, Helen — thanks again for contributing to the information presented for this topic. Much appreciated! :)

[ Gravatar Icon ]

Alex#22

Excellent info! Already implemented this on my site to help people jump to the top of pages.

Very useful. Thanks.

Alex

[ Gravatar Icon ]

Sunny Singh#23

After I realized that this works, I stopped using <a></a>

I also use the name of the section of the site, instead of the domain.
So <body id="www-myunv-com"> would be <body id="main"> or “home” or something.

[ Gravatar Icon ]

Clint#24

Is it possible this doesn’t work in FF on Mac? I’ve tried your CNN link and it just opens up cnn.com as it would have with a nornal link to it… no sign of a footer here (unless i scroll down manually of course).

[ Gravatar Icon ]

Tricia#25

The CNN link didn’t work for me, either, but upon further investigation, the id that CNN uses for their footer is actually #cnn_ftrcntnt, so going to http://www.cnn.com/#cnn_ftrcntnt works. Perhaps they have changed the id since this was written.

[ Gravatar Icon ]

smk#26

@Sunny
The whole point of using your domain name as body id is to create consistent “CSS Signature” for your whole site, so people may override your site style with their browser user.css (or Greasemonkey, or whatever).

E.x.
#www-myunv-com p {
       font-size: 46px; /* because I'm shortsighted */
}

:-)

[ Gravatar Icon ]

Ron oerlemans#27

This doesn’t work in IE8 anymore..

[ Gravatar Icon ]

Jeff Starr#28

@Tricia: Thanks for the heads up - I have updated the article with the new information.

[ Gravatar Icon ]

Andy Ford#29

I also find id-based page anchors handy when doing front-end builds. For example, if you’re quickly iterating the CSS for the footer of a site and refreshing the browser often, you can put the ID in the URL like example.com/#footer. And when you refresh the browser you don’t have to bother with scrolling down to the footer - the browser just jumps down to it.

[ Gravatar Icon ]

Jeff Starr#30

@Andy: Very nice tip :)

[ Gravatar Icon ]

Tricia#31

Oh…and I probably should have added…thanks for the article, I thoroughly enjoyed it. ;)

[ Gravatar Icon ]

Jaina#32

Really very useful! I had no idea and feel a little bit ashamed that I never knew as it feels incredible obivous. Good to learn something new, cheers!

[ Gravatar Icon ]

Jeff Starr#33

@Tricia: Thanks for helping to make it even better :)

@Jaina: I felt the same way when I first discovered this. Good to hear I’m not the only one :)

[ Gravatar Icon ]

Theresa Kilcourse#34

Wow, I can’t tell you how much I appreciate this. Thank you.

Trackbacks / Pingbacks
  1. Links for September 14th | jonathan stegall: creative tension
  2. Twitter Trackbacks for How to simplify your markup using ID for anchors • Perishable Press [perishablepress.com] on Topsy.com
  3. BlogBuzz September 19, 2009
  4. How to simplify your markup using IDs for anchors • Perishable Press « Netcrema – creme de la social news via digg + delicious + stumpleupon + reddit
  5. links for 2010-01-05 | James A. Arconati
Share your thoughts..

Read Comment Policy

Comment Rules: No spam. No profanity. Use your real name. You may use simple HTML tags for style. Wrap all code in <code> tags. Learn more.



Attention: Do NOT follow this link!