Sunday, September 26, 2010

Top-of-page links

Internal page links are sometimes used to create a top-of-page/back-to-top link. This is
particularly handy for websites that have lengthy pages—when a user has scrolled to the
bottom of the page, they can click the link to return to the top of the document, which
usually houses the navigation. The problem here is that the most common internal linking
method—targeting a link at #top—fails in many browsers, including Firefox and Opera.
<a href="#top">Back to top</a>
You’ve likely seen the previous sort of link countless times, but unless you’re using Internet
Explorer or Safari, it’s as dead as a dodo. There are various workarounds, though, one of
which is to include a fragment identifier at the top of the document. At the foot of the
web page is the Back to top link shown previously, and the fragment identifier is placed
at the top of the web page:
<a id="top" name="top"></a>
This technique isn’t without its problems, though. Some browsers ignore empty elements
such as this (some web designers therefore populate the element with a single space); it’s
tricky to get the element right at the top of the page and not to interfere with subsequent
content; and, if you’re working with XHTML Strict, it’s not valid to have an inline element
on its own, outside of a block element, such as p or div.
Two potential solutions are on offer. The simplest is to link the top-of-page link to your
containing div—the one within which your web page’s content is housed. For sites I
create—as you’ll see in Chapter 7—I typically house all content within a div that has an id
value of wrapper. This enables me to easily control the width of the layout, among other
things. In the context of this section of this chapter, the wrapper div also provides something
for a top-of-page link to jump to. Clicking the link in the following code block would
enable a user to jump to the top of the wrapper div, at (or very near to) the top of the
web page.
<a href="#wrapper">Top of page</a>
Note that since standalone inline elements aren’t valid in XHTML Strict, the preceding
would either be housed within a paragraph or a footer div, depending on the site.
Another solution is to nest a fragment identifier within a div and then style the div to sit
at the top left of the web page. The HTML for this is the following:
<div id="topOfPageAnchor">
<a id="top" name="top"> </a>
</div>
In CSS, you would then add the following:
div#topOfPageAnchor {
position: absolute;
top: 0;
left: 0;
height: 0;
}
Setting the div’s height to 0 means it takes up no space and is therefore not displayed; setting
its positioning to absolute means it’s outside the normal flow of the document, so it
doesn’t affect subsequent page content. You can test this by setting the background color
of a following element to something vivid—it should sit tight to the edge of the browser
window edges.

No comments:

Post a Comment