Showing posts with label html. Show all posts
Showing posts with label html. Show all posts

Sunday, September 26, 2010

Creating a drop-down menu

1. Edit the web page. For any link you want to have a drop-down menu spawn from,
nest an unordered list in its parent list item, as per the example in the following
code block.
<li id="servicesPageLink">
<a href="#">Services</a>
<ul>
<li><a href="#">Drop-down link one</a></li>
<li><a href="#">Drop-down link two</a></li>
<li><a href="#">Drop-down link three</a></li>
<li><a href="#">Drop-down link four</a></li>
</ul>
</li>

2. Create the drop-downs. Test your page now, and it will look odd because nested list
items pick up the styles for the standard list items. To start dealing with this, add
position: relative; to the #navigation li rule, which will enable nested
absolute-positioned elements to take their top and left values from their containers
rather than the page as a whole. Then, after the existing rules in the CSS, add the
#navigation li ul rule shown in the following code block. By setting position to
absolute and left to a large negative value, the nested lists (i.e., the drop-down
menus) are placed offscreen by default, but are still accessible to screen readers.
Adding the top border helps visually separate the nested list from its parent button.
#navigation li ul {
border-top: 1px solid #ad3514;
width: 185px;
position: absolute;
left: -10000px
}
Next, add the following rule to bring the nested lists back when you hover the
cursor over the parent list item. Upon doing so, the list item’s descendant list’s
display value is set to block, and it’s displayed directly underneath the parent
item.
#navigation li:hover ul {
display: block;
left: 0;
}

3. Style nested list items and links. Add the following rule to replace the default
background for list items with one specifically for the drop-down menus. The
border-bottom value visually separates each of the list items.
#navigation li li {
background: url(drop-down-menu-background.gif) repeat-y;
border-bottom: 1px solid #ad3514;
}
Next, add the following rule to style nested list item links, overriding the
text-transform and padding values of top-level list items.
#navigation li li a:link, #navigation li li a:visited {
text-transform: none;
padding-left: 10px;
}

4. The final step is to override the hover and active states. For this example, the
background value for top-level lists is overridden and the background image
removed (meaning the hover state for nested list links has no unique background).
To make the hover state stand out, the links are given a vibrant left border. This
also moves the text inward by the width of the border.
#navigation li li a:hover, #navigation li li a:active {
background: none;
border-left: 5px solid #f7bc1d;
}
These property values are common to both states, apart from the border color
(orange for the hover state and red for the active state, roughly matching the colors
applied to the top-level tab icons in the same states, although the orange is
brighter for the drop-downs so that they stand out more); therefore, add the following
rule to change only the left border’s color on the active state:
#navigation li li a:active {
border-left-color: #ed1c24;
}

Creating breadcrumb navigation

1. Add the list. In the HTML document, add the following code for the breadcrumbs.
Note that the last item signifies the current page—this is why it’s not a link.
<ul id="breadcrumbs">
<li><a href="#">Home page</a></li>
<li><a href="#">Reviews</a></li>
<li><a href="#">Live gigs</a></li>
<li>London, 2008</li>
</ul>

2. Add some body padding. Add a padding value to the existing body rule.
body {
font: 62.5%/1.5 Verdana, Arial, Helvetica, sans-serif;
padding: 20px;
}

3. Style the list by adding the following rule. The font-size setting specifies the font
size for the list items, and the margin-bottom setting adds a margin under the list.
ul#breadcrumbs {
font-size: 1.2em;
margin-bottom: 1em;
}

4. Add the following rule to style the list items. By setting display to inline, list
items are stacked horizontally. The background value sets double-arrow.gif as the
background to each list item (ensure it’s in the same directory as the CSS document,
or modify the path accordingly); the positioning values ensure the background
is set at 0 horizontally and 50% vertically, thereby vertically centering it at
the left—at least once no-repeat is set, which stops the background tiling. Finally,
the padding value sets padding at the right of each list item to 10px, ensuring items
don’t touch the subsequent background image; the left padding value of 15px
provides room for the background image, ensuring the list item text doesn’t sit on
top of it.
#breadcrumbs li {
display: inline;
background: url(double-arrow.gif) 0 50% no-repeat;
padding: 0 10px 0 15px;
}

**Note that when list items are displayed inline, the default bullet points are not displayed.
This is one reason why the bullets in this example are background images,
although we also wanted something more visually relevant, right-facing arrows showing
the path direction.

Using HTML lists and CSS to create a button-like vertical navigation bar


1. Create the list structure. Add the following code block to create the structure of
the navigation bar. By using nested lists, you can provide the navigation bar with a
hierarchical structure (and you can style each level in CSS). In this example, the list
has two levels. (Refer to Chapter 3 for an overview of correctly formatting lists.)
This list is nested within a div with an id value of navigation, which we’ll later take
advantage of by using contextual selectors. (For this example, dummy href values
of # are being used, but in a live site, always check that your links lead somewhere!)
<div id="navigation">
<ul>
<li>
<a href="#">Section one</a>
<ul>
<li><a href="#">A link to a page</a></li>
<li><a href="#">A link to a page</a></li>
<li><a href="#">A link to a page</a></li>
<li><a href="#">A link to a page</a></li>
</ul>
</li>
<li>
<a href="#">Section two</a>
<ul>
<li><a href="#">A link to a page</a></li>
<li><a href="#">A link to a page</a></li>
<li><a href="#">A link to a page</a></li>
<li><a href="#">A link to a page</a></li>
</ul>
</li>

<li>
<a href="#">Section three</a>
<ul>
<li><a href="#">A link to a page</a></li>
<li><a href="#">A link to a page</a></li>
<li><a href="#">A link to a page</a></li>
<li><a href="#">A link to a page</a></li>
</ul>
</li>
</ul>
</div>

2. Add some padding to the body element, so page content doesn’t hug the browser
window edges. Also, add the background-color pair shown following:
body {
font: 62.5%/1.5 Verdana, Arial, Helvetica, sans-serif;
padding: 20px;
background-color: #aaaaaa;
}

3. Style the list. Add the following rule to remove the
default bullet points from unordered lists within the navigation
div, define a width for the lists, and also set the
default font style.
#navigation ul {
list-style-type: none;
width: 140px;
font: 1.2em/1 Arial, Helvetica, sans-serif;
}

4. Set an override for nested lists. As you can see from the
previous image, the nested links have much larger text.
This is because font sizes in ems are inherited, and therefore
the font size within the nested lists ends up at
1.2ems multiplied by 1.2ems. By adding the following
rule, the font size of nested lists is reset to 1em, making
nested lists look the same as top-level lists.
#navigation ul ul {
font-size: 1em;
}

5. Style the buttons. Use a contextual selector to style links within the navigation div
(i.e., the links within this list). These styles initially affect the entire list, but you’ll
later override them for level-two links. Therefore, the styles you’re working on now
are intended only for level-one links (which are for sections or categories). This
first set of property/value pairs turns off the default link underline, sets the list
items to uppercase, and defines the font weight as bold.

#navigation a:link, #navigation a:visited {
text-decoration: none;
text-transform: uppercase;
font-weight: bold;
}

6. Set button display and padding. Still within the same rule, set the buttons to
display as block, thereby making the entire container an active link (rather than
just the link text). Add some padding so the links don’t hug the edge of the
container.
#navigation a:link, #navigation a:visited {
text-decoration: none;
text-transform: uppercase;
font-weight: bold;
display: block;
padding: 3px 12px 3px 8px;
}

7. Define colors and borders. Define the button background and foreground colors,
setting the former to gray and the latter to white. Then add borders to create a 3D
effect. Borders can be styled individually. By setting the left and top borders to a
lighter shade than the background, and the right and bottom borders to a darker
shade, a 3D effect is achieved. (Don’t use black and white, because it will make the
result is too harsh.)
#navigation a:link, #navigation a:visited {
text-decoration: none;
text-transform: uppercase;
font-weight: bold;
display: block;
padding: 3px 12px 3px 8px;
background-color: #666666;
color: #ffffff;
border-top: 1px solid #dddddd;
border-right: 1px solid #333333;
border-bottom: 1px solid #333333;
border-left: 1px solid #dddddd;
}

8. Define other link states. The hover state is defined by
just changing the background color, making it slightly
lighter.
#navigation a:hover {
background-color: #777777;
}
The active state enables you to build on the 3D
effect: the padding settings are changed to move the text up and left by 1 pixel, the
background and foreground colors are made slightly darker, and the border colors
are reversed.

#navigation a:active {
padding: 2px 13px 4px 7px;
background-color: #444444;
color: #eeeeee;
border-top: 1px solid #333333;
border-right: 1px solid #dddddd;
border-bottom: 1px solid #dddddd;
border-left: 1px solid #333333;
}

9. Style nested list item links. The selector #navigation li li a enables you to style
links within a list item that are themselves within a list item (which happen to be in
the navigation div). In other words, you can create a declaration for level-two links.
These need to be differentiated from the section links, hence the following rule
setting them to lowercase and normal font weight (instead of bold). The padding
settings indent these links more than the section links, and the background and
foreground colors are different, being very dark gray (almost black) on light gray
rather than white on a darker gray.
#navigation li li a:link, #navigation li li a:visited {
text-decoration: none;
text-transform: lowercase;
font-weight: normal;
padding: 3px 3px 3px 17px;
background-color: #999999;
color: #111111;
}

10. Style nested item hover and active states. This is done in the same way as per the
section links, changing colors as appropriate and again reversing the border colors
on the active state.
#navigation li li a:hover {
background-color: #aaaaaa;
}
#navigation li li a:active {
padding: 2px 4px 4px 16px;
background-color: #888888;
color: #000000;
border-top: 1px solid #333333;
border-right: 1px solid #dddddd;
border-bottom: 1px solid #dddddd;
border-left: 1px solid #333333;
}
The navigation bar is now complete and, as you can see from the following images
(which depict, from left to right, the default, hover, and active states), the buttons
have a tactile feel to them. Should this not be to your liking, it’s easy to
change the look of the navigation bar because everything’s styled in CSS. To expand
on this design, you could introduce background images for each state, thereby
making the navigation bar even more graphical. However, because you didn’t

simply chop up a GIF, you can easily add and remove items from the navigation bar,
just by amending the list created in step 1. Any added items will be styled automatically
by the style sheet rules.

How to find targets for collapsible content scripts

If you want to change your document structure when using the script from the previous
section in this chapter, you need to find the parent/sibling path, in Internet Explorer and in
other browsers. If you’ve a good grasp of JavaScript, this should be simple; however, if you
don’t—or you just want to sanity-check your values—it’s simple to find out what an element’s
parent is, what it’s next sibling is, and various combinations thereof.
First, give your clickable element a unique id value:
<p><a id="linkToggler" href="#" title="Toggle section"
å onclick="toggle(this); return false;">Toggle div 1!</a></p>
Elsewhere within the web page, add the following script:
<script type="text/javascript">
//<![CDATA[
alert(document.getElementById("linkToggler").nodeName);
//]]>
</script>
Before .nodeName, add whatever combination of .parentNode and .nextSibling you
like—here’s an example:
<script type="text/javascript">
//<![CDATA[
alert(document.getElementById("linkToggler").parentNode.
ånextSibling.nextSibling.nodeName);
//]]>
</script>
When you load the web page in a browser, an alert message will be displayed. This will
detail what the target element is, based on the path defined in the previous code block.

Modularizing the collapsible content script

Although the previous script works perfectly well for a single div, it’s awkward if you want
to use several divs over the course of a page. That’s how the old Images from Iceland site
works, and I had to keep track of id names and values while constructing it. However, it is
possible to make a toggler strip more modular, although this relies on keeping document
structure very strict as far as the collapsible sections go. The files for this section are in the
collapsible-div-modular folder within the chapter 5 folder.
The JavaScript is similar to that in the previous example.
function toggle(toggler) {
if(document.getElementById) {
targetElement = toggler.parentNode.nextSibling;
if(targetElement.className == undefined) {
targetElement = toggler.parentNode.nextSibling.nextSibling;
}
if (targetElement.style.display == "block") {
targetElement.style.display = "none";
}
else {
targetElement.style.display = "block";
}
}
}
The main change is that instead of targeting a div with a specific id value, the script
targets an element in relation to the one being used as a toggler, by way of the
parentNode/nextSibling JavaScript properties.
If you look at the HTML document, you’ll see that the parent of the anchor element is the
p element. What the next sibling element is depends on the browser—Internet Explorer
just looks for the next element in the document (div), but other browsers count whitespace
as the next sibling.
<p><a href="#" title="Toggle section" onclick="toggle(this); return
å false;">Toggle div 1!</a></p>
<div class="expandable">
<p>Initially hidden content (div 1) goes here.</p>
</div>
It would be possible to get around this by stripping whitespace. However, a line in the
JavaScript makes this unnecessary.
if(document.getElementById) {
targetElement = toggler.parentNode.nextSibling;
if(targetElement.className == undefined) {
targetElement = toggler.parentNode.nextSibling.nextSibling;
}
The first line of the previous code block sets the target to the next sibling of the parent
element of the link. In Internet Explorer this works, but other browsers find only whitespace.
Therefore, the second line essentially says, “If you find whitespace (undefined),
then set the target to the next sibling on.” It’s a bit of a workaround, but it’s only one line
of JavaScript.
The JavaScript also includes the method used in the preceding “Enhancing accessibility for
collapsible content” section, to make the togglable sections initially invisible in JavaScriptenabled
browsers only. Note that the related CSS is slightly different to that shown in the
previous section—instead of hidden content being in a div with an id value of hiddenDiv,
it’s now in multiple divs, all of which have a class value of expandable. Therefore, the
selector in the CSS rule has been updated accordingly:
.expandable {
display: none;
}
This system enables you to use as many collapsible divs as you like on the page, and you
don’t have to set id values—the toggling is essentially automated. However, as mentioned
earlier, you must ensure that your structure remains the same for each area that can be
toggled, otherwise the script won’t find the correct element to make visible or invisible
when the links are clicked.

Enhancing accessibility for collapsible content

Although the old version of the Images from Iceland site looks good, it has a problem in
common with the previous exercise: when JavaScript is disabled, the initially hidden content
is inaccessible. The Iceland site was quickly knocked together a number of years back
and has been superseded with a new site, but for any site developed today, there should
be no excuses.
In the previous exercise, the hidden content is set to be hidden by default and the display
property is toggled via the JavaScript function. What therefore needs to be done is to
make the content visible by default and then override this, making it invisible, but only if the user has JavaScript. The first thing to do is remove the style attribute from the following
line of code:
<div id="hiddenDiv" style="display: none;">
Next, a style sheet is created (named javascript-overrides.css for this example), with a
rule that targets the relevant div and sets display to none.
#hiddenDiv {
display: none;
}
Finally, amendments are made to the JavaScript file, adding some lines that attach the new
JavaScript document to the web page:
var cssNode = document.createElement('link');
cssNode.setAttribute('rel', 'stylesheet');
cssNode.setAttribute('type', 'text/css');
cssNode.setAttribute('href', 'javascript-overrides.css');
document.getElementsByTagName('head')[0].appendChild(cssNode);
The results of this are the following:
If a user has JavaScript enabled, javascript-overrides.css is loaded, applying the
display value of none to the togglable div.
If a user has JavaScript disabled, javascript-overrides.css is not loaded, meaning
the togglable div contents are visible.
See the collapsible-div-accessible folder within the chapter 5 folder for reference
files.

Collapsible page content : Setting up a collapsible div

1. Examine the script. Open collapsible-div.js. The code enables you to target any
div with a unique id value. Each time the script is run, it determines whether the
display value of the div is set to block (which makes it visible). If it is, the value is
set to none, thereby making it invisible. If it isn’t set to block (which means it’s set
to none), the script sets the value to block.
function swap(targetId){
if (document.getElementById)
{
target = document.getElementById(targetId);
if (target.style.display == "block")
{
target.style.display = "none";
}
else
{
target.style.display = "block";
}
}
}

2. Add a link. Add the code block shown following—when clicked, the link will toggle
the hidden content. The value within the onclick attribute (hiddenDiv, in this
case) is the id value of the div that this link will toggle.
<p><a href="#" title="Toggle section" onclick="toggleDiv('hiddenDiv');
å return false;">Toggle div!</o>

3. Add a div, and give it an id value equal to the onclick value from the previous
step. Within the div, add whatever content you want. The style attribute makes
the div initially hidden.
<p><a href="#" title="Toggle section" onclick="toggleDiv('hiddenDiv');
å return false;">Toggle div!</a></p>
<div id="hiddenDiv" style="display: none;">
<p>Initially hidden content goes here.</p>
</div>

CSS Tutorial : Image maps

Image maps enable you to define multiple links within a single image; for example, if you
have a weather map, you could use an image map to link to each region’s weather forecast;
or if you had a picture of your office, you could use an image map to make each of
the objects clickable, leading to pages explaining more about each of them. Clickable
regions within image maps can be fairly basic—rectangles or circles—or complex polygonal
shapes. Note that there are both server-side and client-side versions of image maps—
server-side image maps are now considered obsolete and pose accessibility problems, and
even client-side image maps tend to be avoided by most designers, although use of alt text
can help them become reasonably accessible.
Regardless of the complexity of the image and the defined
regions, the method of creating an image map remains the
same. To the right is the image used in this section to show
how a basic image map is created. It contains three geometric
shapes that will be turned into clickable hot-spots.
The image is added to the web page in the usual way (and
within a block element, since img is an inline element), but
with the addition of a usemap attribute, whose value must be
preceded by a hash sign (#).
<div id="wrapper">
<img src="image-map-image.gif" alt="Shapes" width="398" height="398"
å usemap="#shapes" />
</div>
The value of the usemap attribute must correlate with the name and id values of the associated
map element. Note that the name attribute is required for backward compatibility,
whereas the id attribute is mandatory.
<map id="shapes" name="shapes">
</map>
The map element acts as a container for specifications regarding the map’s active areas,
which are added as area elements.
<map id="shapes" name="shapes">
<area title="Access the squares page." shape="rect"
å coords="29,27,173,171" href="square.html" alt="A square" />
<area title="Access the circles page" shape="circle"
å coords="295,175,81" href="circle.html" alt="A circle" />
<area title="Access the triangles page" shape="poly"
å coords="177,231,269,369,84,369" href="triangle.html"
å alt="A triangle" />
</map>
Each of the preceding area elements has a shape attribute that corresponds to the
intended active link area:
rect defines a rectangular area; the coords (coordinates) attribute contains two
pairs that define the top-left and bottom-right corners of the rectangle in terms of
pixel values (which you either take from your original image or guess, should you
have amazing pixel-perfect vision).
circle is used to define a circular area; of the three values within the coords
attribute, the first two define the horizontal and vertical position of the circle’s
center, and the third defines the radius.
poly enables you to define as many coordinate pairs as you wish, which allows you
to define active areas for complex and irregular shapes—in the previous code
block, there are three pairs, each of which defines a corner of the triangle.
Creating image maps is a notoriously tedious process, and it’s one of the few occasions
when I advise using a visual web design tool, if you have one handy, which can be used to
drag out hot-spots. However, take care not to overlap defined regions—this is easy to do,
and it can cause problems with regard to each link’s active area. If you don’t have such a
tool handy, you’ll have to measure out the coordinates in a graphics package.


**Note:  that some browsers will place a border around the image used for an
image map. This can be removed by using CSS to set the image’s border to 0
(either via applying a class to the image, or via a contextual selector).

Enhancing skip navigation with a background image

1. Position the skipNav div. Add the following link to remove the skipNav div from
the document flow and position it at the top of the web page. The width and
text-align property values stretch the div to the full width of the browser window
and center the text horizontally, respectively.
#skipLink {
position: absolute;
top: 0;
left: 0;
width: 100%;
text-align: center;
}
2. Style the skip navigation link. Add the following rule to style the link within the
skipLink div. By setting display to block, the active area of the link stretches to
fill its container, thereby effectively making the entire containing div clickable. The
padding-bottom setting is important, because this provides space at the bottom of
the div for displaying the background image used for the hover state, added in the
next step. The color value is black (#000000) at this point, which ensures that the
text fits happily within the space available above the page content. (This may
change for users with non-default settings, but for the default and first zoom setting,
it’ll be fine.)
#skipLink a:link, #skipLink a:visited {
display: block;
color: #000000;
font: 1.0em Arial, Helvetica, sans-serif;
padding-top: 5px;
padding-bottom: 20px;
}
3. Recolor the skip navigation link. Change the color property so that the link blends
into the background.
#skipLink a:link, #skipLink a:visited {
display: block;
color: #fefefe;
font: 1.0em Arial, Helvetica, sans-serif;
padding-top: 5px;
padding-bottom: 20px;
}
4. Define the hover and focus states. Add the following rule to set the style for the
hover and focus states. This essentially makes the text visible (via the color setting)
and defines a background image—a wide GIF89 image with a downwardfacing
arrow at its center now appears when the user places their mouse cursor
over the top of the web page.
#skipLink a:hover, #skipLink a:focus {
color: #000000;
background: url(skip-navigation-down-arrow.gif) 50% 100% no-repeat;
}

Enhanced link accessibility and usability

The title attribute

Regular users of Internet Explorer for
Windows may be familiar with its habit of
popping up alt text as a tooltip. This has
encouraged web designers to wrongly fill alt
text with explanatory copy for those links that
require an explanation, rather than using the
alt text for a succinct overview of the image’s
content. Should you require a pop-up, add a
title attribute to your surrounding a element
to explain what will happen when the
link is clicked. The majority of web browsers
display its value when the link is hovered over
for a couple of seconds (see right), although
some older browsers, such as Netscape 4,
don’t provide this functionality.
<a href="large-image.html" title="Click to view a larger image">
å<img src="image.jpg" alt="This is some text that explains what
å the image is" width="400" height="300" /></a>
There are a few things to be mindful of when using title attributes. The first is that
behavior varies slightly between browsers, and the positioning and style of the tooltip cannot
be controlled. Internet Explorer exhibits some particularly quirky behavior. In addition
to displaying alt text as a tooltip, alt text defined within an img element will override (and
therefore be displayed instead of) title text for a surrounding a element. However, if the
title and alt attributes are both placed within the img element, the title attribute wins
out. Therefore, some technically unnecessary duplication of content is required to ensure
compliance from Internet Explorer. Also, Microsoft’s browser does not display title text
when you mouse over area elements within image maps.













Using accesskey and tabindex

I’ve bundled the accesskey and tabindex attributes because they have similar functions—
that is, enabling keyboard access to various areas of the web page. Most browsers enable
you to use the Tab key to cycle through links, although if you end up on a web page with
dozens of links, this can be a soul-destroying experience. (And before you say “So what?”
you should be aware that many web users cannot use a mouse. You don’t have to be
severely disabled or elderly to be in such a position either—something as common as
repetitive strain injury affects plenty of people’s ability to use a mouse.)
The accesskey attribute can be added to anchor and area elements. It assigns an access
key to the link, whose value must be a single character. In tandem with your platform’s
assigned modifier key (Alt for Windows and Ctrl for Mac), you press the key to highlight or
activate the link, depending on how the browser you’re using works.
<a href="index.html" accesskey="/">Home page</a>
An ongoing problem with access keys is that the shortcuts used to activate them are
mostly claimed by various technologies, leaving scant few characters. In fact, research conducted
by WATS.ca (www.wats.ca/show.php?contentid=32) concluded that just three
characters were available that didn’t clash with anything at all: /, \ and ]. This, combined
with a total lack of standard access key assignments/bindings, has led to many accessibility
gurus conceding defeat, admitting that while there’s a definite need for the technology, it’s
just not there yet.
The tabindex attribute has proved more successful. This is used to define the attribute’s
value as anything from 0 (which excludes the element from the tabbing order, which can
be useful) to 32767, thereby setting its place in the tab order, although if you have 32,767
tabbable elements on your web page, you really do need to go back and reread the earlier
advice on information architecture (see Chapter 1). Note that tab orders needn’t be consecutive,
so it’s wise to use tabindex in steps of ten, so you can later insert extra ones
without renumbering everything.
Not all browsers enable tabbing to links, and others require that you amend some preferences
to activate this function, and so tabindex ultimately only really comes in handy
when working with forms, as you’ll see in Chapter 8. When used for too many other elements,
you also run the risk of tabindex values hijacking the mouse cursor, meaning that
instead of the Tab key moving the user from the first form field to the second, it might end
up highlighting something totally different, elsewhere on the page. What’s logical to some
people—in terms of tab order—may not be to others, so always ensure you test your websites
thoroughly, responding to feedback.

Skip navigation links
Designers who work with CSS layouts tend to focus on information structure, rather than
blindly putting together layouts in a visual editor. This is good from an accessibility standpoint,
because you can ensure information is ordered in a logical manner by checking its
location in the code. However, when considering alternate browsers, it’s clear that some of
the information on the page will be potentially redundant. For example, while a user surfing
with a standard browser can ignore the masthead and navigation in a split second, rapidly
focusing on the information they want to look at, someone using a screen reader will
have to sit through the navigation links being read out each time, which can prove
extremely tedious if there are quite a few links.
Various solutions exist to help deal with this problem, and although you can use CSS to
reorder the page information (most commonly by placing the code for the masthead at
the end of the HTML document and then using absolute positioning to display it at the top
when the page is viewed in a browser), it’s more common to use what’s typically referred
to as skip navigation

The difference between a and a:link

Many designers don’t realize the difference between the selectors a and a:link in CSS.
Essentially, the a selector styles all anchors, but a:link styles only those that are clickable
links (i.e., those that include an href attribute) that have not yet been visited. This means
that, should you have a site with a number of fragment identifiers, you can use the a:link
selector to style clickable links only, avoiding styling fragment identifiers, too. (This prevents
the problem of fragment identifiers taking on underlines, and also prevents the
potential problem of user-defined style sheets overriding the a rule.) However, if you
define a:link instead of a, you then must define the visited, hover, and active states,
otherwise they will be displayed in their default appearances. This is particularly important
when it comes to visited, because that state is mutually exclusive to link, and doesn’t
take on any of its styling. Therefore, if you set font-weight to bold via a:link alone, visited
links will not appear bold (although the hover and active states will for unvisited
links—upon the links being visited, they will become hover and active states for visited
links and will be displayed accordingly).

Correctly ordering link states

The various states have been defined in a specific order in the previous example: link,
visited, hover, focus, active. This is because certain states override others, and those
“closest” to the link on the web page take precedence.
There is debate regarding which order the various states should be in, so I can only provide
my reasoning for this particular example. It makes sense for the link to be a certain
color when you hover over it, and then a different color on the active state (when
clicked), to confirm the click action. However, if you put the hover and active states in
the other order (active, hover), you may not see the active one when the link is clicked.
This is because you’re still hovering over the link when you click it.
The focus state is probably primarily use keyboard users, and so they won’t typically see
hover anyway. However, for mouse users, it makes logical sense to place focus after hover,
because it’s a more direct action—in other words, the link is selected, ready for activation
during the focus state; but if you ordered the states focus, hover, a link the cursor is
hovering over would not change appearance when focused, which from a user standpoint
is unhelpful.
However, there is a counter argument that recommends putting focus before hover, so
that when an already focused link (or potentially any other focused element for non-IE
browsers) is hovered over, it will change from the focused state to indicate that it is now
being hovered over. Ultimately, this is a chicken-and-egg scenario—do you want a hovered
link to change from hover to focus to active? The focus will get lost somewhere in there
until the link is depressed (and the active state removed), by which time the link will be
in the process of being followed.
In the end, the decision should perhaps rest with how you’re styling states and what information
you want to present to the user, and often the focus state is a duplication of hover
anyway, for the benefit of keyboard users. And on some occasions, it doesn’t matter too
much where it’s put, if the styling method is much different from that for other states—
for example, when a border is applied to focus, but a change of color or removal of
underlines is used for the other states. However, if you decide on LVFHA or some other
order, you’ll have to make your own way of remembering the state order!

Defining link states with CSS

CSS has advantages over the obsolete HTML method of defining link states. You gain control
over the hover and focus states and can do far more than just edit the state colors—
although that’s what we’re going to do first.
Anchors can be styled by using a tag selector:
a {
color: #3366cc;
}
In this example, all anchors on the page—including links—are turned to a medium blue.
However, individual states can be defined by using pseudo-class selectors (so called
because they have the same effect as applying a class, even though no class is applied to
the element):
a:link {
color: #3366cc;
}
a:visited {
color: #666699;
}
a:hover {
color: #0066ff;
}
a:focus {
background-color: #ffff00;
}
a:active {
color: #cc00ff;
}

Web Navigation types

Inline navigation: General links within web page content areas
Site navigation: The primary navigation area of a website, commonly referred to as
a navigation bar
Search-based navigation: A search box that enables you to search a site via terms
you input yourself


Inline navigation
Inline navigation used to be the primary way of navigating the Web, which, many moons
ago, largely consisted of technical documentation. Oddly, inline navigation—links within a
web page’s body copy—is less popular than it once was. Perhaps this is due to the increasing
popularity of visually oriented web design tools, leading designers to concentrate more
on visuals than usability. Maybe it’s because designers have collectively forgotten that links
can be made anywhere and not just in navigation bars. In any case, links—inline links in
particular—are the main thing that differentiates the Web from other media, making it
unique. For instance, you can make specific words within a document link directly to
related content. A great example of this is Wikipedia (www.wikipedia.org), the free encyclopedia.


Site navigation
Wikipedia showcases navigation types other than inline. To the left, underneath the logo,
is a navigation bar that is present on every page of the site, allowing users to quickly access
each section. This kind of thing is essential for most websites—long gone are the days
when users often expected to have to keep returning to a homepage to navigate to new
content.
As Wikipedia proves, just because you have a global navigation bar, that doesn’t mean you
should skimp on inline navigation. In recent times, I’ve seen a rash of sites that say things
like, “Thank you for visiting our website. If you have any questions, you can contact us byclicking the contact details link on our navigation bar.” Quite frankly, this is bizarre. A better
solution is to say, “Thank you for visiting our website. If you have any questions, please
contact us,” and to turn “contact us” into a link to the contact details page. This might
seem like common sense, but not every web designer thinks in this way.

Search-based navigation
Wikipedia has a search box within its navigation sidebar. It’s said there are two types of
web users: those who eschew search boxes and those who head straight for them. The
thing is, search boxes are not always needed, despite the claims of middle managers the
world over. Indeed, most sites get by with well-structured and coherent navigation.
However, sites sometimes grow very large (typically those that are heavy on information
and that have hundreds or thousands of pages, such as technical repositories, review
archives, or large online stores, such as Amazon and eBay). In such cases, it’s often not feasible
to use standard navigation elements to access information. Attempting to do so leads
to users getting lost trying to navigate a huge navigation tree.
Unlike other types of navigation, search boxes aren’t entirely straightforward to set up,
requiring server-side scripting for their functionality. However, a quick trawl through
a search engine provides many options, including Google Custom Search Engine
(www.google.com/coop/cse/) and Yahoo Search Builder (http://builder.search.yahoo.
com/m/promo).

Backward compatibility with fragment identifiers

In older websites, you may see a slightly different system for accessing content within a
web page, and this largely involves obsolete browsers such as Netscape 4 not understanding
how to deal with links that solely use the id attribute. Instead, you’ll see a fragment
identifier, which is an anchor tag with a name attribute, but no href attribute. For instance,
a fragment identifier for the first answer is as follows:
<p><a id="answer1" name="answer1">Answer 1!</a></p>
The reason for the doubling up, here—using both the name and id attributes, is because
the former is on borrowed time in web specifications, and it should therefore only be used
for backward compatibility.

Internal page links

Along with linking to other documents, it’s possible to link to another point in the same
web page. This is handy for things like a FAQ (frequently asked questions) list, enabling the
visitor to jump directly to an answer and then back to the list of questions; or for top-ofpage
links, enabling a user single-click access to return to the likely location of a page’s
masthead and navigation, if they’ve scrolled to the bottom of a long document.
When linking to other elements on a web page, you start by providing an id value for any
element you want to be able to jump to. To link to that, you use a standard anchor element
(<a>) with an href value equal to that of your defined id value, preceded by a hash
symbol (#).
For a list of questions, you can have something like this:
<ul id="questions">
<li><a href="#answer1">Question one</a></li>
<li><a href="#answer2">Question two</a></li>
<li><a href="#answer3">Question three</a></li>
</ul>
Later on in the document, the first two answers might look like this:
<p id="answer1">The answer to question 1!</p>
<p><a href="#questions">Back to questions</a></p>
<p id="answer2">The answer to question 2!</p>
<p><a href="#questions">Back to questions</a></p>
As you can see, each link’s href value is prefixed by a hash sign. When the link is clicked,
the web page jumps to the element with the relevant id value. Therefore, clicking the
Question one link, which has an href value of #answer1, jumps to the paragraph with the
id value of answer1. Clicking the Back to questions link, which has an id value of
#questions, jumps back to the list, because the unordered list element has an id of
questions.

**NOTE : It’s worth bearing in mind that the page only jumps directly to the linked element if
there’s enough room underneath it. If the target element is at the bottom of the web
page, you’ll see it plus a browser window height of content above.

Creating and styling web page links

With the exception of search boxes, which are forms based on and driven by server-side
scripting, online navigation relies on anchor elements. In its simplest form, an anchor element
looks like this:
<a href="http://www.friendsofed.com/">A link to the friends of ED
å website</a>

The href attribute value is the URL of the destination document, which is often another
web page, but can in fact be any file type (MP3, PDF, JPEG, and so on). If the browser can
display the document type (either directly or via a plug-in), it does so; otherwise, it downloads
the file (or brings up some kind of download prompt).
There are three ways of linking to a file: absolute links, relative links, and root-relative
links. We’ll cover these in the sections that follow, and you’ll see how to create internal
page links, style link states in CSS, and work with links and images. We’ll also discuss
enhanced link accessibility and usability, and link targeting.

Absolute links
The preceding example shows an absolute link, sometimes called a full URL, which is typically
used when linking to external files (i.e., those on other websites). This type of link
provides the entire path to a destination file, including the file transfer protocol, domain
name, any directory names, and the file name itself. A longer example is
<a href="http://www.wireviews.com/lyrics/instar.html">Instar lyrics</a>
In this case, the file transfer protocol is http://, the domain is wireviews.com, the directory
is lyrics, and the file name is instar.html.
If you’re linking to a website’s homepage, you can usually leave off the file name, as in the
earlier link to the friends of ED site, and the server will automatically pick up the default
document—assuming one exists—which can be index.html, default.htm, index.php,
index.asp, or some other name, depending on the server type. However, adding a trailing
slash after the domain is beneficial (such as http://www.wireviews.com/). If no default
document exists, you’ll be returned a directory listing or an error message, depending on
whether the server’s permissions settings enable users to browse directories.

Relative links
A relative link is one that locates a file in relation to the current document. Taking the
Wireviews example, if you were on the instar.html page, located inside the lyrics directory,
and you wanted to link back to the homepage via a relative link, you would use the
following code:
<a href="../index.html">Wireviews homepage</a>
The index.html file name is preceded by ../, which tells the web browser to move up one
directory prior to looking for index.html. Moving in the other direction is done in the
same way as with absolute links: by preceding the file name with the path. Therefore, to
get from the homepage back to the instar.html page, you would write the following:
<a href="lyrics/instar.html">Instar lyrics</a>
In some cases, you need to combine both methods. For instance, this website has HTML
documents in both the lyrics and reviews folders. To get from the instar.html lyrics
page to a review, you have to go up one level, and then down into the relevant directory
to locate the file:
<a href="../reviews/alloy.html">Alloy review</a>

Root-relative links
Root-relative links work in a similar way to absolute links, but from the root of the website.
These links begin with a forward slash, which tells the browser to start the path to the file
from the root of the current website. Therefore, regardless of how many directories deep
you are in the Wireviews website, a root-relative link to the homepage always looks
like this:
<a href="/index.html">Homepage</a>
And a link to the instar.html page within the lyrics directory always looks like this:
<a href="/lyrics/instar.html">Instar lyrics</a>
This type of link therefore ensures you point to the relevant document without your
having to type an absolute link or mess around with relative links, and is, in my opinion,
the safest type of link to use for linking to documents elsewhere on a website. Should a
page be moved from one directory to one higher or lower in the hierarchy, none of the
links (including links to style sheets and script documents) would require changing.
Relative links, on the other hand, would require changing; and although absolute links
wouldn’t require changing, they take up more space and are less modular from a testing
standpoint; if you’re testing a site, you don’t want to be restricted to the domain in
question—you may wish to host the site locally or on a temporary domain online so that
clients can access the work-in-progress creation.
All paths in href attributes must contain forward slashes only. Some software—
notably older releases from Microsoft—creates and permits backward slashes (e.g.,
lyrics\wire\154.html), but this is nonstandard and does not work in non-Microsoft
web browsers.

Monday, September 20, 2010

Working with style sheets for print

In the old days (and, frankly, in the not-so-old days, since the practice somehow survives),
designers often worked on so-called printer-friendly sites, run in parallel with the main
site. However, if you’re using CSS layouts, it’s possible to create a style sheet specifically for
print, which you can use to dictate exactly which elements on the page you want to print,
which you want to omit, and how you want to style those that can be printed.
As mentioned earlier in the book, a print style sheet is attached to web pages using the
following HTML:
<link rel="stylesheet" type="text/css"media="print"
å href="print-style-sheet.css" />
The media attribute value of print restricts the CSS solely to print, and within the print
style sheet, you define styles specifically for print, such as different fonts and margins. In
the example in the download files, I’ve used a version of the business website, which you
can access via the sme-website-print folder in the chapter 10 folder. The print style
sheet is sme-print.css, and if you compare it to the main style sheet, you’ll see that it’s
much simpler and massively honed down.
The defaults section houses a single body rule, defining padding (to take into account varying
printer margins, 5% is a good horizontal padding to use), the background color (white
is really the only choice you should use, and it’s usually the default, but setting it explicitly
ensures this is the case), the text color (black is best for contrast when printing), and the
font. There’s absolutely no point in trying to ape your onscreen design and typography in
print—instead, use values that enhance the printed version. In the example’s body rule
(shown in the following code block), serif fonts are defined for font-family, because serifs
are easier to read in print. Note that you’re not only restricted to web-safe fonts at this
point either—you can define choices based on fonts that come with the default install of
Windows and Mac OS, hence the choices of Baskerville (Mac) and Palatino Linotype
(Windows), prior to Times New Roman and Times.
body {
padding: 0 5%;
background: #ffffff;
font-family: Baskerville, "Palatino Linotype", "Times New Roman",
å "Times", serif;
line-height: 16pt;
}
In the structure section, the #masthead declaration sets display to none. That’s because
this area of the page is of no use for printed output—you simply don’t need website masthead
and navigation offline. (This is, of course, a generalization, and in rare cases this may
not be applicable; however, in the vast, vast majority of websites I’ve created, the printed
version has not required the masthead and navigation links.) Note that if other areas aren’t
required, just use a grouped selector instead of this rule with a lone selector, as shown in
the following code block (which isn’t in the example CSS):
#element1, #element2, .class1, .class2 {/* these items won't be
å printed */
display: none;
}Because pixel values don’t tend to translate to print well, some settings may need to be
redefined. An example in this case is the two-column section of the page. The widths and
margins were initially defined in pixels, but in the print CSS, it makes more sense to define
these values in percentages. (Note that the 9.99% value is there in case of rounding
errors.)
.columnLeft, .columnRight {
float: left;
width: 45%;
}
.columnLeft {
margin-right: 9.99%;
}
In the links and navigation section, only one rule remains. While links are of no real use
offline, it’s still a good idea to make it apparent what text-based content was originally a
link, in order for people to be able to find said links should they want to, or for reasons of
context. Just ensuring the default underline is in place should do, and that can be done via
the following rule:
a:link, a:visited {
text-decoration: underline;
}
For browsers other than Internet Explorer (although JavaScript workarounds exist for IE
compatibility—e.g., see www.grafx.com.au/dik//printLinkURLs.html), you can also provide
the href values alongside any printed links by using the following code:
a:link:after, a:visited:after {
content: " (" attr(href) ") ";
font-size: 90%;
}
In terms of fonts, keeping things simple makes sense. It’s also worth noting that because
you’re working with print, sizes in points are more useful than sizes in pixels. (Note that
in the body rule, the line-height value was 16pt, not 16px or 1.6em.) Therefore, the
font-size values all reflect that. Note in the p.footer rule that floated content still needs
clearing in the print style sheets.
The final section, images, is not changed much. The images within the columns were
deemed superfluous, and so display has been set to none for .columnLeft img,
.columnRight img. Elsewhere, the margins on the floated image have been set to values in
centimeters (cm) and the border value for #content img is in millimeters (mm), since we’re
working in print. (Values in pixels are permitted, but they tend to be less accurate when
working with print style sheets—for example, if elements have a one-pixel border, they
may not all be even when printed.)
One final thing that’s useful to know is how to create print-only content. In this example,
removing the masthead from the print output has also removed the site’s corporate ID. A
cunning way to bring this back is to create a black-and-white version of the company logo,
and add that as the first item on the web page, within a div that has an id value of
printLogo.
<div id="printLogo">
<img src="assets/we-lay-floors-bw-logo.gif" alt="Web Lay Floors,
å Inc. logo" width="267" height="70" />
</div>
Then, in the main style sheet, create a rule that displays this element offscreen when the
page is loaded in a browser window.
#printLogo {
position: absolute;
left: -1000px;
}
The content will then show up in print, but not online. Note, however, that you should be
mindful to not hide weighty images in this manner, otherwise you’ll compromise download
speeds for anyone using your website in a browser, only for making things slightly better
for those printing the site. A small, optimized GIF should be sufficient.
If there’s other content you want to hide in this manner, you can also create a generic
printOnly class to apply to elements you want hidden in the browser, but visible in print.
The following CSS rule applied to your screen style sheet would be sufficient for doing
this:
.printOnly {
display: none;
}
The reason for not using this generic method with the logo is because at the time of writing,
Opera appears to only print images cached from the normal page view—in other
words, if the image isn’t displayed in the standard browser window, Opera won’t print it.
Therefore, if using the generic printOnly class, be aware that any images hidden won’t
print in Opera, but text will.
An example of how the print style sheet looks is shown in the following screenshot.
 

Note that you can take things further in terms of layout, but it’s best to keep it simple.
Also, ensure that you use the Print Preview functions of your browser test suite to thoroughly
test your print style sheet output and ensure that there are no nasty surprises for
visitors to your site. Ultimately, it’s worth the extra hassle—just amending the fonts and
page margins and removing images and page areas that are irrelevant to the printed version
of the site not only improves your users’ experience, but also makes the site seem
more professional.

Using CSS to wrap text around images

You can use the float and margin properties to enable body copy to wrap around an
image. The method is similar to the pull quote example in the previous chapter, so we
won’t dwell too much on this. Suffice to say that images can be floated left or right, and
margins can be set around edges facing body copy in order to provide some whitespace.
For example, expanding on the previous example, you could add the following rules to
ensure that the surrounding body copy doesn’t hug the image:
.photo {
border-width: 8px 8px 20px 8px;
border-style: solid;
border-color: #ffffff;
float: right;
margin-left: 20px;
margin-bottom: 20px;
}
This results in the following effect shown in the following image.
 
See using-css-to-wrap-around-images.html, using-css-to-wrap-around-images.css,
and sunset.jpg in the chapter 4 folder for a working example of this page.

Using CSS when working with images

Applying CSS borders to images
Alternatively, you could set borders to be on by default, and override them in specific
areas of the website via a rule using grouped contextual selectors:
img {
border: 1px solid #000000;
}
#masthead img, #footer img, #sidebar img {
border: 0;
}
Finally, you could override a global border setting by creating a noBorder class and then
assigning it to relevant images. In CSS, you’d write the following:
.noBorder {
border: 0;
}
And in HTML, you’d add the noBorder class to any image that you didn’t want to have a
border:
<img class="noBorder" src="sunset.jpg" height="200" width="400"
å alt="A photo of a sunset" />
Clearly, this could be reversed (turning off borders by default and overriding this with, say,
an addBorder style that could be used to add borders to specific images). Obviously, you
should go for whichever system provides you with the greatest flexibility when it comes to
rapidly updating styles across the site and keeping things consistent when any changes
occur. Generally, the contextual method is superior for achieving this.
Although it’s most common to apply borders using the shorthand shown earlier, it’s possible
to define borders on a per-side basis, as demonstrated in the “Using classes and CSS
overrides to create an alternate pull quote” exercise in Chapter 3. If you wanted to style a
specific image to resemble a Polaroid photograph, you could set equal borders on the top,
left, and right, and a larger one on the bottom. In HTML, you would add a class attribute
to the relevant image:
<img class="photo" src="sunset.jpg" height="300" width="300"
å alt="Sunset photo" />
In CSS, you would write the following:
.photo {
border-width: 8px 8px 20px;
border-style: solid;
border-color: #ffffff;
}The results of this are shown in the image to the
right. (Obviously, the white border only shows if
you have a contrasting background—you wouldn’t
see a white border on a white background!)
Should you want to, you can also reduce the declaration’s
size by amalgamating the border-style
and border-color definitions:
.photo {
border: solid #ffffff;
border-width : 8px 8px 20px;
}

You may have noticed earlier that I didn’t mention the border attribute when working
through the img element. This is because the border attribute is deprecated; adding borders
to images is best achieved and controlled by using CSS. (Also, because of the flexibility
of CSS, this means that if you only want a simple surrounding border composed of flat
color, you no longer have to add borders directly to your image files.) Should you want to
add a border to every image on your website, you could do so with the following CSS:
img {
border: 1px solid #000000;
}
In this case, a 1-pixel solid border, colored black (#000000 in hex), would surround every
image on the site. Using contextual selectors, this can be further refined. For instance,
should you only want the images within a content area (marked up as a div with an id
value of content) to be displayed with a border, you could write the following CSS:
div#content img {
border: 1px solid #000000;
}