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

Saturday, October 23, 2010

Css Tutorial : Be Careful with Fonts

Remember that the alternative fonts suggested here need to be used with caution. Ensure
sensible alternatives are listed in the font-family sequence, and remember that a font displayed
on a Mac can look significantly different, or even be unavailable, on a PC. It is advisable to edit
your font sequences at the testing stage to see how your alternative fonts work for you. For
example, Georgia may be your second-choice font, but be sure it suits your design should the
first choice be unavailable.

Convey the Mood with the Right Font

The right font for the right job communicates with the user instantly. Your text is the first ingredient
to appear as the page is downloaded, and it can instantly tell the user whether the web
site is serious or friendly, modern or traditional, formal or casual. Do you want the web site to
give the impression of a newspaper or journal, newsletter or fact sheet? If you do not want to
convey such an authoritative standpoint, then maybe something humorous or light-hearted is
needed? Choosing the right font or combination of fonts is key to creating the right impression
from the outset.

Monday, October 4, 2010

Css tutorial : Centering with margin: auto

The best way to center an element with CSS is to use the auto value for left and right margins.
For modern browsers, all this requires is a set width rule (as without it the box would naturally
stretch to fit its container—in this case the browser window) and the left and right margins
given the auto value. Building upon the earlier example, we have the following rule:
/* Container for centering all our content */
#container {
width: 400px;
margin: 10px auto 10px auto;
padding: 20px;
border: 1px solid #000;
background: #CCC;
}
Most browsers are happy with this, although IE5/Win fails miserably, usually aligning the
element to the left. At the time of writing, most IE users are using IE6, and IE7 is on the way, but
the percentage of IE5 users is significant enough to warrant consideration.
There is a way of making it work for IE5/Win, and it’s quite simple. The trick is to make use
of the text-align property in the container’s parent element (in this case that is the <body>) to
center the container. The downside is that all child elements within <body> will now correctly
inherit that value and center all their content, which isn’t good. Therefore text-align: left is
applied to all main division elements to counter the centering:
/* Define default values for the whole site */
body {
text-align: center;
}
/* Container for centering all our content */
#container {
width: 400px;
margin: 10px auto 10px auto;
padding: 20px; border: 1px solid #000;
background: #CCC;
text-align: left;
}
This approach ensures that the container is centered horizontally in the browser window
whatever browser is used, and acts as the perfect basis for any centered design (see Figure 3-6).

Careful with the Cascade

It can sometimes be hard to track the cascade across several style sheets. For example, if two
selectors have matching properties but varying values, e.g., each instance of a selector was made up
of font-family, color, and background, but with different values for each, the selector in the
style sheet with the highest hierarchy would win out and be rendered. Things get even more
interesting when each selector has unique properties.
Let’s clarify this with an example. Imagine that in a modular style sheet such as forms.css
you have defined a class called highlight as follows:
/* Highlight important form information */
.highlight {
color:#F00;
font-style:italic;
text-decoration:underline;
}
Should there be no other instance of that selector in any style sheets higher up the hierarchy,
highlight will indeed be rendered in red italicized text with a neat underline. However,
imagine that a few weeks later in external.css, a style sheet of more hierarchical importance,
you’ve forgotten about the original class and decide to reuse highlight as follows:
/* Highlight author’s name underneath articles */
.highlight {
color:#F00;
font-style:normal;
}
First, the cascade dictates that the font-style value for highlight in external.css (fontstyle:
normal;) is of greater importance than the value in forms.css (font-style: italic;).
Therefore, all instances of highlight sitewide will be normal red text, not italicized. Without
realizing it, you have just turned all your lovely italicized form text into boring normal text, and
you probably won’t notice until you revisit your forms in your browser.
And to further illustrate this pitfall, the new highlight class in external.css does not define a
value for text-decoration, so the normal red text you wished to create will be underlined, taking
that value from forms.css. Sure, your new highlight class takes precedence in the hierarchy,
but unless you turn off the underline in external.css, the cascade will still find its way to the
original rule and look for anything not being overruled.

Overriding Base Styling with Classes

/* Default styling for paragraphs */
p {
color:#F00;
font-size:12px;
}
/* Use this style to turn anything light gray */
.bleached {
color:#CCC;
}
All paragraphs will still be red by default, but this can still be overridden when necessary
by identifying an element with the bleached class, as in this (X)HTML:
<p>This paragraph has red text.</p>
<p class="bleached">This paragraph has light gray text.</p>
The second paragraph will now be light gray, as the color declaration in bleached overrides
the red. Note that the paragraph is still rendered 12 pixels high, as bleached does not redefine
font-size. Add a font-size declaration in bleached, and that value will override the original
size for all paragraphs identified with class="bleached".

Combining IDs with Multiple Classes

Classes are especially useful when you wish to have control over a number of elements. Consider
the following drinks list, the source code for which is available in the drinks.html file:
<ul id="drinks">
<li class="alcohol">Beer</li>
<li class="alcohol">Spirits</li>
<li class="mixer">Cola</li>
<li class="mixer">Lemonade</li>
<li class="hot">Tea</li>
<li class="hot">Coffee</li>
</ul>
Note first that the unordered list (<ul>) is given a unique ID. Thus, id="drinks" will not be
used again on the page at any time, allowing that particular list to be styled uniquely. Note also
that Beer and Spirits are within list elements defined with class="alcohol", Cola and Lemonade
are within list elements defined with class="mixer", and finally Tea and Coffee are defined in
list elements with class="hot". This allows each drinks group to be treated individually.
The CSS declares that the default text for that list will be red, so any list items without a
class attribute will default to red text:
/* Drinks list styling */
ul#drinks {
color:#F00;
}
Next, the classes for each drink type are defined with unique shades of gray for font color:
/* Define alcohol color */
.alcohol {
color:#333;
}
/* Define mixer color */

.mixer {
color:#999;
}
/* Define hot drinks color */
.hot {
color:#CCC;
}
The result sees the list of items move through shades of gray (defined by the classes).
Any further drinks added to the list can be assigned to a particular drinks group, such as
<li class="alcohol">Wine</li>. Thus a logical color key is established using simple CSS classes.



**■Tip Before adding a class to an element, be sure that the element needs it. Too often web designers
overuse classes when the (X)HTML is already providing more than enough hooks for the CSS. Make sure that
the element cannot be targeted using a descendant selector or other method before opting for a class. This
will help keep your code lean and make future redesigning much easier.

Combining IDs with Selectors

Existing or new IDs can be combined with selectors in the style sheet to add further control. In
the following example, the base CSS defines all h2 headings as dark gray and 16 pixels in size:
/* Basic heading style */
h2 {
color:#333;
font-size:16px;
}


That is fine for most uses of <h2>, but let’s say the main <h2> on your page (the title of
an article) needs to be emphasized with a different color. This calls for a new rule where the
selector is defined in the form element#name:
/* Adjust the color of h2 when used as a title */
h2#title {
color:#F00;
}
Here the new rule will override the default <h2> color (color: #333;) with red (color: #F00;)
whenever an <h2> is identified with id="title" in the (X)HTML. The new rule does not redefine
font-size, so that will be carried over and unchanged. Simply add the unique identifier to
the page:
<h2 id="title">Title Of My Article</h2>
Remember that title is a unique identifier, so it cannot be used again within that template.
Any other instances of <h2> on the page will be rendered with the default styling.

Friday, October 1, 2010

Problems with CSS hover menus (drop-downs)

Problem: The browser supports :hover only on links, rather than on any element, thereby
making drop-downs like that in Chapter 5’s “Creating a drop-down menu” exercise fail.


Solution: Use some kind of JavaScript fallback system. There are various options for this,
but the simplest is the solution offered by Peter Nederlof at www.xs4all.nl/~peterned/
csshover.html. All you need to do is download either csshover.htc or csshover2.htc,
place it somewhere within your site’s hierarchy, and then link to it through a rule in a style
sheet linked via a conditional comment.
body {
behavior: url(csshover2.htc);
}
Another solution is to use HTML Dog’s Suckerfish Dropdowns (www.htmldog.com/
articles/suckerfish/dropdowns/), which works nicely all the way back to Internet
Explorer 5, and uses perfectly valid CSS.

Problems with iframes in Css

Problem: Internet Explorer spawns both horizontal and vertical scroll bars when content is
larger than the declared width or height. This means that if your iframe is 200 pixels high,
but your content is 400 pixels high, you’ll end up with a vertical scroll bar and a horizontal
one, even if your content is narrower than the iframe dimensions. Other browsers don’t
make this mistake, displaying only the relevant scroll bar. Also, styling iframes can cause
problems. Turning off the default border is a good move, because it looks clunky. Adding
a border using CSS should be possible by applying it directly to the iframe (via a class or
iframe tag selector); in practice, however, this partially fails in Internet Explorer versions 6
and below, creating an ugly gap between your scroll bars and iframe borders (which happens
to be the same size as the defined border).


Solution: If you know your iframe content is always going to be too large for the iframe,
set scrolling="yes" in the iframe start tag. Alternatively, add a conditional comment in
the head of the iframe content document, with the following code, experimenting with
the width property until the scroll bar disappears. If you use similar iframes on a number
of pages, you should instead assign a class value to the body element of the relevant pages
and define the html, body rule in an IE 6-and-below-specific style sheet.

<!--[if lte IE 6]>
<style type="text/css">
html, body {margin:0; width:180px;}
</style>
<![endif]-->
For border styles, you can work around the problem in one of two ways: you can override
the original border value, setting it to 0 for Internet Explorer 6 and below; or you can nest
the iframe in a div and provide the div with a border instead.

Dealing with rounding errors

Problem: In liquid layouts with floated elements, rounding errors sometimes cause the
widths of the elements to add up to more than 100%. This causes one of the floated elements
to wrongly stack under the others. This problem is known to affect all versions of
Internet Explorer. For an example, see the following image (from the “Creating flanking
sidebars” exercise in Chapter 7), in which the right-hand sidebar is wrongly sitting underneath
the left-hand sidebar.
Solution: As explained in the focus point within the “Creating flanking sidebars” exercise,
rounding errors can be dealt with by reducing one of the percentage values of a column
by as little as 0.0001%, although sometimes this reduction needs to be increased.

Thursday, September 30, 2010

Dealing with Internet Explorer bugs

As mentioned elsewhere, Microsoft made a huge leap forward with Internet Explorer 7,
but it’s still not without its problems. Also, because Microsoft’s browser enjoyed such an
immense market share for so long, older versions remain in use for years, sometimes
enjoying a share of the market that manages to eclipse every other browser apart from the latest release of Internet Explorer. With this in mind, along with the sad fact that
Microsoft’s browser has been the least compliant one out there for a long time now, this
section is dedicated to exploring how to deal with the most common Internet Explorer
bugs. These are all worth committing to memory, because if you’re working on CSS layouts,
these bugs will affect your designs at some point, and yet most of the fixes are
extremely simple.

DEALING WITH BROWSER QUIRKS : Weeding out common errors

Testing in browsers isn’t everything; in fact, you may find that your site fails to work for no
reason whatsoever, tear your hair out, and then find the problem lurking in your code
somewhere. With that in mind, you should either work with software that has built-in and
current validation tools (many have outdated tools, based on old versions of online equivalents),
or bookmark and regularly use the W3C’s suite of online tools: the Markup
Validation Service (http://validator.w3.org/), CSS Validation Service (http://jigsaw.
w3.org/css-validator/), Feed Validation Service (http://validator.w3.org/feed/),
Link Checker (http://validator.w3.org/checklink), and others (www.w3.org/QA/Tools/)
as relevant.
Other useful online services include WDG Link Valet (www.htmlhelp.com/tools/valet/),
WDG HTML Validator (www.htmlhelp.com/tools/validator/), and Total Validator (www.
totalvalidator.com/). Accessibility-oriented services include HP’s Color Contrast Verification
Tool (www.hp.com/hpinfo/abouthp/accessibility/webaccessibility/color_tool.html);
Etre’s Colour Blindness Simulator (www.etre.com/tools/colourblindsimulator/); and
the Cynthia Says Portal Tester (www.cynthiasays.com/fulloptions.asp), which can
aid you in Section 508 and WAI (Web Accessibility Initiative—see www.w3.org/WAI/)
compliance.
Here are some of the more common errors you might make that are often overlooked:

Spelling errors: Spell a start tag wrong and an element likely won’t appear; spell an
end tag wrong and it may not be closed properly, wrecking the remaining layout. In
CSS, misspelled property or value names can cause rules—and therefore entire layouts—
to fail entirely. British English users should also remember to check for and
weed out British spellings—setting colour won’t work in CSS, and yet we see that
extra u in plenty of web pages (which presumably have their authors scratching
their heads, wondering why the colors aren’t being applied properly).

Incorrect use of symbols in CSS: If a CSS rule isn’t working as expected, ensure
you’ve not erred when it comes to the symbols used in the CSS selector. It’s a
simple enough mistake to use # when you really mean . and vice versa.

Lack of consistency: When working in XHTML, all elements and attributes must be
lowercase. In CSS, tag selectors should also be lowercase. However, user-defined id
and class values can be in whatever case the author chooses. Ultimately, decide
on a convention and stick to it—always. If you set a class value to myvalue in CSS
and myValue in HTML, chances are things won’t work. For the record, I prefer
lowerCamelCase, but there’s no reason for choosing a particular case.

Not closing elements, attributes, and rules: An unclosed element in HTML may
cause the remainder of the web page (or part of it) to not display correctly.
Similarly, not closing an HTML attribute makes all of the page’s content until the
next double quote part of the attribute. Not closing a CSS rule may cause part or
all of the style sheet to not work. Note that CSS pairs that aren’t terminated with a
semicolon may cause subsequent rules to partially or wholly fail. A good tip to
avoid accidentally not closing elements or rules is to add the end tag/closing
bracket immediately after adding the start tag/opening bracket. This also helps to
avoid incorrect nesting of elements.

Multiple rule sets: In CSS, ensure that if you use a selector more than once, any
overrides are intentional. It’s a common error for a designer to duplicate a rule set
and have different CSS property values conflicting in different areas of the CSS.
Errors with the head and body elements: As stated earlier in the book, HTML content
should not appear outside of the html element, and body content should not
appear outside of the body element. Common errors with these elements include
placing content between the closing head element tag (</head>) and the body start
tag (<body>), and including multiple html and body elements.

Inaccessible content: Here, we’re talking in a more general sense, rather than about
accessibility for screen reader users. If you create a site with scrollable areas,
ensure users can access the content within, even if browser settings aren’t at their
defaults. Problems mostly occur when overflow is set to hidden. Similarly,
textarea elements that don’t have properly marked-up cols and rows settings
will often be tiny when viewed without CSS (these attributes are functional as well
as presentational). The same is true for text input fields without a defined size
attribute.

Dead links: These can take on many forms, such as a link to another page being
dead, an image not showing up, or external documents not being accessible by the
web page. If a JavaScript function isn’t working for some reason, try checking to see
whether you’ve actually linked it—in some cases, the simpler and most obvious
errors are the ones that slip through the net. Also, if things aren’t working on a live
site, check the paths—you may have accidentally created a direct link to a file on
your local machine, which obviously won’t be accessible to the entire Internet.
Spaces within href values or the original file names can also be accidentally overlooked.

Whitespace errors: In CSS, do not place whitespace between class/id indicators and
the selector name, or between numerals and units for measurements. However, do
not omit whitespace from between contextual selectors, otherwise you’ll “combine”
them into a new, probably unknown, one.

Using multiple units: In CSS, a value can only accept a single unit—the likes of
50%px can cause a rule to partially or wholly fail.

Wednesday, September 29, 2010

Advanced form layout with CSS

A common way of laying out forms is to use a table to line up the labels and form controls,
although with the output being non-tabular in nature, this method is not recommended
(CSS should be used for presentation, including positioning elements on a web page)—it’s
provided here to show a (partial) table layout that can be replicated in CSS. For our first
three fields, a table-based form may have something like this:
<fieldset>
<legend>Personal information</legend>
<table class="formTable" cellpadding="0" cellspacing="0" border="0"
å summary="A contact details form.">
<tr>
<th scope="row">
<label for="realname">Name</label></th>
<td><input class="formField" type="text" id="realname"
å name="realname" size="30" /></td>
</tr>
<tr>
<th scope="row"><label for="email">Email address</label></th>
<td><input class="formField" type="text" id="email" name="email"
å size="30" /></td>
</tr>
<tr>
<th scope="row"><label for="phone">Telephone</label></th>
<td><input class="formField" type="text" id="phone" name="phone"
å size="30" /></td>
</tr>
</table>
</fieldset>

Because a class value was added to the
table, the contextual selector .formTable
th can be used as the selector for styling the
form labels, defining the text-align property,
along with other CSS properties such as
font-weight. Applying a padding-right value to these cells also produces a gap to the
right of the label cells. Another contextual selector, .formTable td, can then be used to
style the cells—for example, to add padding at the bottom of each cell. The image to the
right shows these styles applied to the various elements in the previous code block, along
with the styles shown in the “Adding styles to forms” section.
.formTable td {
padding: 0 0 5px 0;
}
.formTable th {
padding-right: 10px;
text-align: right;
font-weight: bold;
}
Although forms are not tabular in nature, using a table to create a form can result in a
pleasing visual appearance, with the labels right-aligned and placed next to their associated
labels. This kind of layout can be replicated using CSS, via a structure built from divs
to replace the table rows. This method retains semantic integrity, via the semantic relationship
created by the label and associated field’s id. Using CSS for form layout also
brings with it the benefit of being able to rapidly restyle and move form components.
<form action="http://www.yourdomain.com/cgi-bin/FormMail.cgi"
å method="post">
<fieldset>
<legend>Personal information</legend>
<div class="row clearFix">
<label for="realname">Name</label> <input class="formField"
å type="text" id="realname" name="realname" size="30" />
</div>
<div class="row clearFix ">

<label for="email">Email address</label> <input class="formField"
å type="text" id="email" name="email" size="30" />
</div>
<div class="row clearFix ">
<label for="phone">Telephone</label> <input class="formField"
å type="text" id="phone" name="phone" size="30" />
</div>
</fieldset>
</form>
Various styles are then defined in CSS. The form itself has its width restricted, and label
elements are floated left, the text within aligned right, and the font-weight property set
to bold. The width setting is large enough to contain the largest of the text labels.
form {
width: 350px;
}
label {
float: left;
text-align: right;
font-weight: bold;
width: 95px;
}
The form controls—the input elements—are floated right. Because only input elements
within the div rows should be floated (rather than all of the input elements on the page),
the contextual selector .row input is used. (The containing divs have a class value of
row.) The width setting is designed to provide a gap between the labels and input elements.
.row input{
float: right;
width: 220px;
}
Finally, to make a gap between the rows, a .row class
is added and given a margin-bottom value.
.row {
margin-bottom: 5px;
}

The method works fine in all browsers except Internet Explorer, which doesn’t apply
margin-bottom correctly. However, the slightly different layout in Internet Explorer can
largely be fixed by adding the following in a style sheet attached via an IE-specific conditional
comment:
.row {
clear: both;
margin-top: 5px;
}
Alternatively, add the following:
.clearFix {
display: inline-block;
}

Working with forms

In this section, we’ll work through how to create a form and add controls. We’ll also look
at how to improve form accessibility by using the tabindex attribute, and the label,
fieldset, and legend elements.
As suggested earlier in the chapter, the best way of getting user feedback is through an
online form that the user fills in and submits. Fields are configured by the designer,
enabling the site owner to receive specific information. However, don’t go overboard: provide
users with a massive, sprawling online form and they will most likely not bother filling
it in, and will go elsewhere.
Similarly, although you can use JavaScript to make certain form fields required, I’m not a
fan of this technique, because it annoys users. Some sites go overboard on this, “forcing”
users to input a whole bunch of details, some of which may simply not be applicable to the
user. In such cases, users will likely either go elsewhere or insert fake data, which helps
no one.
So, keep things simple and use the fewest fields possible. In the vast majority of cases, you
should be able to simply create name, e-mail address, and phone number fields, and
include a text area that enables users to input their query. 

Creating a form

Form controls are housed within a form element, whose attributes also determine the
location of the script used to parse it (see the “Sending feedback” section later in the
chapter). Other attributes define the encoding type used and the method by which the
browser sends the form’s data to the server. A typical start tag for a form therefore looks
like this:
<form action="http://www.yourdomain.com/cgi-bin/FormMail.cgi"
å method="post">

Adding controls

Some form controls are added using the input element. The type attribute declares what
kind of control the element is going to be. The most common values are text, which produces
a single-line text input field; checkbox and radio, which are used for multiplechoice
options; and submit, which is used for the all-important Submit button.
Other useful elements include select, option, and optgroup, used for creating pop-up
lists, and textarea, which provides a means for the user to offer a multiple-line response
(this is commonly used in online forms for a question area). The basic HTML for a form
may therefore look like the following, producing the page depicted in the following screen
grab.
<form action="http://www.yourdomain.com/cgi-bin/FormMail.cgi"
å method="post">
<p><strong>Name</strong><br />
<input type="text" name="realname" size="30" /></p>
<p><strong>Email address</strong><br />
<input type="text" name="email" size="30" /></p>
<p><strong>Telephone</strong><br />
<input type="text" name="phone" size="30" /></p>
<p><strong>Are you a Web designer?</strong><br />
<input type="radio" name="designer" value="yes" />Yes |
å <input type="radio" name="designer" value="no" />No</p>
<p>What platform do you favor?<br />
<select name="platform">
<option selected="selected">Windows</option>
<option>Mac</option>
<option>Linux</option>
<option>Other</option>
</select></p>
<p><strong>Message</strong><br />
<textarea name="message" rows="5" cols="30"></textarea></p>
<p><input type="submit" name="SUBMIT" value="SUBMIT" /></p>
</form>
The bulk of the HTML is pretty straightforward. In each case, the name attribute value
labels the control, meaning that you end up with the likes of Telephone: 555 555 555 in
your form results, rather than just a bunch of answers. For multiple-option controls (check
boxes and radio buttons), this attribute is identical, and an individual value attribute is set
in each start tag.
By default, controls of this type—along with the select list—are set to off (i.e., no values
selected), but you can define a default option. I’ve done this for the select list by setting
selected="selected" on the Windows option. You’d do the same on a radio button
to select it by default, and with a check box you’d set checked="checked".
Some of the attributes define the appearance of controls: the input element’s size attribute
sets a character width for the fields, while the textarea’s rows and cols attributes set
the number of rows and columns, again in terms of characters. It’s also worth noting that
any content within the textarea element is displayed, so if you want it to start totally
blank, you must ensure that there’s nothing—not even whitespace—between the start and
end tags. (Some applications that reformat your code, and some website editors, place
whitespace here, which some browsers subsequently use as the default value/content of
the textarea. This results in the textarea’s content being partially filled with spaces, and
anyone trying to use it may then find their cursor’s initial entry point partway down the
text area, which can be off-putting.)Long-time web users may have noticed the omission of a Reset button in this example.
This button used to be common online, enabling the user to reset a form to its default
state, removing any content they’ve added. However, I’ve never really seen the point in
having it there, especially seeing as it’s easy to click by mistake, resulting in the user having
to fill in the form again, hence its absence from the examples in this chapter. However,
if you want to add such a button, you can do so by using the following code:
<input type="reset" name="RESET" value="RESET" />


Improving form accessibility

Although there’s an onscreen visual relationship between form label text and the controls,
they’re not associated in any other way. This sometimes makes forms tricky to use for
those people using screen readers and other assistive devices. Also, by default, the Tab key
cycles through various web page elements in order, rather than jumping to the first form
field (and continuing through the remainder of the form before moving elsewhere). Both
of these issues are dealt with in this section.

The label, fieldset, and legend elements
The label element enables you to define relationships between the text labeling a form
control and the form control itself. In the following example, the Name text is enclosed in a
label element with the for attribute value of realname. This corresponds to the name and
id values of the form field associated with this text.
<p><label for="realname">Name</label><br />
<input type="text" name="realname" id="realname" size="30" /></p>
Most browsers don’t amend the content’s visual display when it’s nested within a label
element, although you can style the label in CSS. However, most apply an important
accessibility benefit: if you click the label, it gives focus to the corresponding form control
(in other words, it selects the form control related to the label). Note that the id attribute—
absent from the form example earlier in the chapter—is required for this. If it’s
absent, clicking the text within the label element won’t cause the browser to do anything.
The fieldset element enables you to group a set of related form controls to which you
apply a label via the legend element.
<fieldset>
<legend>Personal information</legend>
<p><label for="realname">Name</label><br />
<input type="text" id="realname" name="realname" size="30" /></p>
<p><label for="email">Email address</label><br />
<input type="text" id="email" name="email" size="30" /></p>
<p><label for="phone">Telephone</label><br />
<input type="text" id="phone" name="phone" size="30" /></p>
</fieldset>
As you can see from the previous screenshot, these elements combine to surround the relevant
form fields and labels with a border and provide the group with an explanatory title.

Adding tabindex attributes

The tabindex,used to define the page’s element tab order, and its
value can be set as anything from 0 to 32767. Because the tabindex values needn’t be
sequential, it’s advisable to set them in increments of ten, enabling you to insert others
later, without having to rework every value on the page. With that in mind, you could
set tabindex="10" on the realname field, tabindex="20" on the email field, and
tabindex="30" on the phone field (these field names are based on their id/name values
from the previous example). Assuming no other tabindex attributes with lower values are
elsewhere on the page, the realname field becomes the first element highlighted when the
Tab key is pressed, and then the cycle continues (in order) with the email and phone fields.
Note that whenever using tabindex, you run the risk of 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. Generally, it makes sense to use the
value only for form fields, and then with plenty of care.

Scrollable content areas with CSS

Although iframes can be useful for practical reasons, many designers use them for aesthetic
reasons, in order to provide a lot of information on a single page. For example,
iframes are popular for lists of news items because they enable many hundreds of lines of
text to be contained in a small area. However, if this is your reason for using an iframe,
you’re better off replacing it with a div and using CSS to control the overflow. If you use
this method, the content will remain part of the web page, which is better for accessibility
and site maintenance.
To do this, create a div with a unique class value:
<div class="scrollableContent">
[content...]
</div>
Then style it in CSS—the rule provides the div’s dimensions and determines how the div’s
overflow works:
.scrollableContent {
width: 200px;
height: 200px;
overflow: auto;
}
When overflow is set to auto, scroll bars only appear when the content is too large for the
set dimensions of the div. Other available values are hidden (display no scroll bars),
scroll (permanently display both scroll bars), and visible (render content outside of the
defined box area). Adding some padding, especially at the right-hand side of the scrollable
content box, helps improve the area aesthetically, ensuring that content doesn’t hug the
scroll bar.
.scrollableContent {
width: 200px;
height: 200px;
overflow: auto;
padding: 0 10px 0 0;
}
Note that by also using PHP includes (see PHP Solutions, by David Powers, for more on
those), you can even make scrollable content separate from the main web page, thereby
emulating another aspect of an iframe, but without resorting to using frames at all.
<div class="scrollableContent">
<?php @include $_SERVER['DOCUMENT_ROOT'] .
å "/include/document-name.php"; ?>
</div>

In this code block, @ suppresses errors, so if it didn’t work, you’d receive no indication—
removing @ would show any errors. Also, the document root setting sets the include to
take the HTML/document root instead of the server root as the starting point for looking
for the included file (when the file path starts with a /), so be aware of that when defining
paths. An alternative would be to use a relative path, such as include/document-name.
php. This would work without pointing to the server at the document root (so long as the
path was correct).
Another more accessible option than using iframe elements is to use the object element
to embed an external HTML document within a region of the page—when combined with
the scrolling div method shown in this section, it pretty much provides all the benefits of
an iframe with very few of the drawbacks (the content is on the page, unlike with frames
and iframes—their content remains external).
The following code block shows how an object element can be added to the page. Note
the alternate content within the object element, displayed if the browser cannot show the
object. This can be used to directly link to the file in the data attribute.
<object data="a-file.html" type="text/html">
<p>[alternate content]</p>
</object>
Like other elements, the object element can be styled using CSS, although Internet
Explorer adds a border, so you need to overwrite existing border settings using conditional
comments (see Chapter 9 for more on those) to prevent a double border. Also, if the content
is too large for the object dimensions, it will scroll in whatever direction is needed,
unless you explicitly set overflow to hidden; however, this setting doesn’t work in Internet
Explorer and Opera.

Working,with,internal,frames (iframes)

The only type of frames in general use today are iframes. These enable you to update a
page section without reloading the rest of it. Popular sites using iframes include
Newstoday (www.newstoday.com/) and Pixelsurgeon (www.pixelsurgeon.com/), the latter
of which uses a small inline frame to display its news feed.
In a more general sense, this can be handy for enabling users to update a portion of a
site’s design without touching the rest of the design, and without resorting to a costly content
management system. However, there are superior and more accessible alternatives to
this system, as you’ll see later in the chapter.
An iframe can be placed anywhere within a web page. Its available attributes are outlined
in Appendix A (XHTML Reference), but two worth mentioning here are width and height,
which define the dimensions of the iframe. Set these with caution, because it’s annoying if
an iframe is bigger than the viewable area, or if the content of the iframe is too big for its
defined dimensions. Note that these attributes can be omitted from HTML and instead
defined in CSS (by way of an iframe tag selector or by applying a class to the iframe).
Here’s some example code for an iframe:
<iframe src="internal_news.html" name="news" width="200" height="200"
å scrolling="yes" frameborder="0">Your browser doesn't support
å iframes. Please <a href="internal_news.html">click here
å to see the iframe's content</a>.</iframe>
Note the succinct content for the iframe, which enables non-frames-compatible devices to
directly access the content of the iframe—compliant devices ignore this.

Working with columns

The vast majority of print media makes heavy use of columns. The main reason for this is
that the eye generally finds it easier to read narrow columns of text than paragraphs that
span the width of an entire page. However, when working with print, you have a finite and
predefined area within which to work, and by and large, the “user” can see the entire page
at once. Therefore, relationships between page elements can be created over the entire
page, and the eye can rapidly scan columns of text.
On the Web, things aren’t so easy. Web pages may span more than the screen height,
meaning that only the top portion of the page is initially visible. Should a print page be
translated directly to the Web, you may find that some elements essential for understanding
the page’s content are low down the page and not initially visible. Furthermore, if using
columns for text and content, you may end up forcing the user to scroll down and up the
page several times. Finally, it’s almost impossible—due to the variations in output from
various browsers and platforms—to ensure that text columns are the same length anyway.
(CSS should eventually enable designers to more easily deal with these problems, but it
will be some time before such solutions are supported.)
Therefore, web designers tend to eschew columns—but let’s not be too hasty. It’s worth
bearing in mind something mentioned earlier: the eye finds it tricky to read wide columns
of text. Therefore, it’s often good practice to limit the width of body copy on a website to
a comfortable reading width. Also, if you have multiple pieces of content that you want
the user to be able to access at the same time, columns can come in handy. This can be
seen in the following screenshots from the Thalamus Publishing website (www.
thalamus-books.com).As you can see, the main, central column of the About page provides an overview of the
company. To the left is the site-wide search and an advertisement for one of the company’s
publications; and to the right is a sidebar that provides ancillary information to support
the main text. This provides text columns that are a comfortable, readable width, and
enables faster access to information than if the page content were placed in a linear, vertical
fashion.

Sunday, September 26, 2010

Creating a vertical navigation bar with collapsible sections

1. Set up the JavaScript. Create a new JavaScript document and attach it to the HTML
file via a script element in the head of the document. (In the example files, this
document has been named vertical-navigation-bar.js.) First, add the
JavaScript lines first shown in the “Enhancing accessibility for collapsible content”
section:
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);
Next, add the toggler script shown in the “Modularizing the collapsible content
script” section, but amend the target element as shown:
function toggle(toggler) {
if(document.getElementById) {
targetElement = toggler.nextSibling;
if(targetElement.className == undefined) {
targetElement = toggler.nextSibling.nextSibling;
}
if (targetElement.style.display == "block")
{
targetElement.style.display = "none";
}
else
{
targetElement.style.display = "block";
}
}
}

2. Amend the list. To each top-level navigation link, add the onclick attribute, as
shown following. And to each second-level list that you initially want to be invisible,
add the class attribute shown. For any list you want to be visible, instead add
style="display: block;".
<li>
<a href="#" onclick="toggle(this); return false;">Section one</a>
<ul class="collapsibleList">
<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>

3.
Add a style sheet. Create and save the style sheet document javascriptoverrides.
css, and add the following rule to initially hide any lists with the
collapsibleList class value in JavaScript-enabled browsers.
#navigation ul.collapsibleList {
display: none;
}
The following images show the results (which depict, from left to right, the
default, hover, and active states).

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;
}

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;
}