Click here to monitor SSC
  • Av rating:
  • Total votes: 58
  • Total comments: 8
William Brewer

Advice on CSS you'll wish your mother told you

21 May 2010

William Brewer turns a jaundiced eye to the task of laying out  web pages using CSS, and gives some nuggets from years of occasional page design. It is, of course, set with a a stylesheet he's come up with to demo a few of his points.

There are several vital pieces of advice about laying out CSS pages that I wish I’d been told before I started making a mess of using CSS styles. This isn’t really just a series of tips for beginners to CSS, but a list of those facts that can get missed for ages, but which end up becoming  incredibly useful in day-to-day work with websites. Now I've been doing the layout of text in websites for some time, I can begin to really appreciate these nuggets of advice. Every professional designer of websites will know all this, but you and I are just ordinary developers who are expected to know everything, aren't we, so I'll just spell it out as briefly as I can.

1/ Make sure all your elements inherit their typography from the Base Font.

You are laying out a page and decide to lay out a dictionary list. Great. Looking good, but when you test it in IE, it is the wrong font.  So you put in a CSS style to tell it the right font, right? No.  You’ll just get a different nasty surprise when you test it with Safari or Opera, or you subsequently change the overall text font.

You should, instead,  make sure that all the elements you’re using inherit their styles from their parent. This allows you to put all the fiddly style-stuff in the BODY tag, or the DIV container.  This means it is all easier to change when someone takes a dislike to the font, or the font settings you've chosen.

You can tell when a designer has been stung one too many times. They generally have the following ‘reset’ style. It is great for taking out quirks.

html, body, div, span, object, iframe,

h1, h2, h3, h4, h5, h6, p, blockquote, pre,

a, abbr, acronym, address, code,

del, dfn, em, img, q, dl, dt, dd, ol, ul, li,

table, caption, tbody, tfoot, thead, tr, th, td ,hr{

  font-weight: inherit;

  font-style: inherit;

  font-size: 100%;

  font-family: inherit;

}

This means you can confidently set the basic font styles in just one place. You’ll probably pack in some more styles for your grand initial reset whilst you’re about it.

2/  To ensure cross-browser compatibility for a page design, reset the default settings to render the same

This is related closely to the previous item, but its aims are to make all the tags render in a consistent way across browsers. It is tempting to assume that every browser uses the same style for each tag. Sadly, there has never been any agreement between the browsers on how it should be done. Therefore, your  first part of your stylesheet ought to do this.

The best reset routine is by Eric Meyer, the CSS guru, though the most CSS frameworks have them too. (CSS frameworks are great to pull ideas and practices from. I like, and have used, the Azbuka CSS Typographical Base Rendering Library and the blueprint CSS Framework ). I've combined the 'Inherit' and 'Reset' definition into one for the sample stylesheet for this article, which you can download to look at in the speech bubble at the head of the article.

3/ Use the ‘semantic’ tag elements that the HTML standard provides rather than creating SPAN classes, where possible.

Tags should, where possible,  indicate the meaning of the textual information rather than merely to define its presentation (look).  The fewer purely ‘presentation’ tags that are there, the easier it is to alter the look of your site.  

So what are these tags? If text  has an address in it, use the <address> tag, if it is a long quotation, use <Blockquote>, if you have a dictionary-style list, use <dl>,<dd> and <dt>. If it is a heading, just don’t think of avoiding the use of <H1> to <H6>. If it is a list, however you want it to look, use <LI> along with <ol> or <UL>. Don’t think of using text outside <p> tags.  Where text within a paragraph needs to be enhanced, use the inline text tags such as <abbr> (an abbreviation or acronym) <cite> (yes, a citation), <code> (computer code), <dfn> (a definition) , <em>, <kbd>, <pre>, <samp> (sample computer code within text), <q>(a quote in text),  <small>, <strong> (important text) <del> (deleted),  <ins> (inserted)  and <var>.

Why? It is so that your text still works in old browsers or with text readers for blind people, to help provide other aids for people with sight problems, to give useful information to browsers, spell checkers, translation systems and search-engine indexers. They usually take fewer keystrokes too. An example of a useful semantic tag  is the old <abbr> tag that has a TITLE attribute which works on all browsers. If you add something like this to your stylesheet, you’ll get tooltips on your abbreviations or acronyms…

abbr {

  border-bottom: 1px dotted #333;

  cursor: help;

  }

I've done this with the CSS acronym in this article just to illustrate what happens. There is a limit to what you can do purely with these semantic tags. When you reach this limit, then you have <SPAN> and <DIV>, the great general-purpose inline and block structural elements. They are only structural if you assign classes to them that will tell anyone maintaining the page what they mean. It is possible to use nothing else, but I wouldn't advise it!

the <DIV> is a great way of dividing your text into semantic blocks. Because you can define a class that apply only to elements that are nested within another element of a particular class, you can completely redefine the way that a tag works within another element such as a DIV. For example, the code blocks in this article are done very simply just by defining a code class. Then we redefine the way that the <P> tag works inside any element with that class assigned to it. So here is the CSS code that does it, rendered by itself!

 .code {

DISPLAY: block;

BORDER-BOTTOM: silver 1px solid;

TEXT-ALIGN: left;

BORDER-LEFT: silver 1px solid;

MARGIN-LEFT: 20px;

BORDER-TOP: silver 1px solid;

BORDER-RIGHT: silver 1px solid;

FONT: 11px "Courier New", Courier, monospace;

BACKGROUND: whitesmoke;

PADDING: 10px;

}

 .code p {

MARGIN-TOP: 0px;

MARGIN-BOTTOM: 0px;

MARGIN-LEFT: 0px;

PADDING: 0px;

}

This means that, by nesting areas in DIVs, or changing the attributes of other block elements such as DL, OL, or UL, you have precise control over the way that any of the semantic tags are rendered, in any part of your page, and it is all relatively easy to modify when someone requires that you change the appearance of the site. 

4/ Elements can take more than one class.

You can assign a whole space-delimited list of classes to an element. Like good designers, we make SPANs for any inline strings within a paragraph block that need to be enhanced in a particular way.  It sounds daft, but few examples point out that, unlike Microsoft Word,  you can have as many classes defined for a tag, and the browser  does its best with the space-delimited list. DIVs of a number of different types need to be indented. So do other block elements. You only need one .indented class and just add it to the block elements that you need to indent, even if they already have a class assigned to them. Be economical. There’s no need to create lots of classes. Just keep as many as you can remember.

5/ Think in terms of generic classes where possible before using  element-specific  classes.

Many classes that are designed for block elements such as <DIV>s can apply to a range of  other types of block elements. The same applies to inline elements.  If you define a generic class, you’ll often find they can be easily recycled for different circumstances without you having to define another class. To assign a class to a particular tag can tie you down unnecessarily.

6/ Stick to a particular capitalisation for your class names.

Yes, different doctypes have different defaults for the case-sensitivity of the CSS classes. Your  code will work in one page, but not in another. Best do your testing in a doctype that is case-sensitive.

7/ When you’re rapidly designing CSS, use inline style blocks

When you have the perfect stylesheet, then it is time to deploy it to the whole site by putting it in a file and linking to it as an external stylesheet. Before then, when you’re actively working on it, use inline stylesheets. I find it easiest to work on a small sample, using an inline style-sheet, using TopStyle CSS Editor, until I've nailed a style down. While you are fighting with a recalcitrant bit of CSS that simply refuses to play ball in all the main browsers, then a small sample, and an inline style with a good CSS editor, and the odds are then on your side.

<style type="text/CSS">

<!--

/* styles go here */

-->

</style>

The problem I've found in development work when you are l linking to an external stylesheet is that when you make changes to the stylesheet and you want to see what happens it can get cached on the server side or on the browser. This can slow things down. When you're finished making changes, then update the CSS file and you're done!

8/ Use lists for anything that looks like a list. Remember that you don’t need them bullets.

It is easy to forget that you can change the style of a list in a number of different ways.  Lists can run across the page

  • One
  • Two
  • Three
  • Four
  • Five
  • Six

or down the page.---

  • One
  • Two
  • Three
  • Four
  • Five
  • Six

... and they don’t need to be bulleted or numbered either.  You can even get the effect of a menu system purely with lists.  There are great sites with a range of ideas for lists. Try out Listamatic, for example. It is very tempting to start using fancy HTML or tables when all you need is a good list, with the right styles

9/ Attach a style to an ID rather than a tag if you intend a style to work with just a particular element in the DOM.

If you need to make sure that a particular style can only be applied to a single element, then you can define a style using a # prefix. This attaches the style to the element with that particular ID. I feel that this is occasionally rather overdone, but it is a good way of flagging to anyone who is inspecting your stylesheet that this is definitely your intention.

#currentmonth {

     background-color: silver;

}

10/ Encourage a feeling of guilt and self-loathing  when you use a table as a structural element to locate the layout in the right place. It is supposed to be for tables.

We are some way yet before we can separate the structure of text from its presentation, but the use of nested tables for laying out the page should be a last resort.   I used to think that this was just the ravings of blokes in sandals. The problems become apparent if you need to make changes to a page that has a large number of nested tables to arrange the content.  Page elements  start leaping around the page like spring bunnies. Tables will do things that are difficult to do with CSS, but CSS allows you to do things you can only dream of when in your ‘Table-phase’  of designing web-pages.

11/ Relative and absolute addressing represent powerful magic.

A lot of grief and fiddling with tables can be saved by using absolute addressing for elements that are placed within a containing block element. Let's imagine you want to do something like this...

what we have is an outer 'relative' which has within it two 'absolute' positioned columns which we can place as precisely as we need

.but what makes it magical is that most HTML editors such as 'Frontpage' will allow you to move and resize these blocks with the mousepointer!

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer eget libero eget sem sagittis dignissim quis in orci. Praesent eget lacus nunc. Mauris id nibh tellus, nec pharetra nisi. Nulla dolor nunc, vulputate quis scelerisque sit amet, bibendum nec tortor. In bibendum ligula et velit lobortis vel lobortis odio adipiscing. Pellentesque habitant morbi tristique senectus

This is achieved simply, with the following code.

<DIV style="POSITION: relative; WIDTH: 640px">
<DIV style="POSITION: absolute; WIDTH: 305px; TOP: 1px; LEFT: 1px">
<P>what we have is an outer 'relative' which has within it two 'absolute' positioned columns which we can place as precisely as we need</P></DIV>
<DIV style="POSITION: absolute; WIDTH: 224px; TOP: 80px; LEFT: 81px">.but what makes it magical is that most HTML editors such as 'Frontpage' will allow you to move and resize these blocks with the mousepointer!</DIV>
<DIV style="BORDER-BOTTOM: medium none; POSITION: absolute; BORDER-LEFT: medium none; WIDTH: 305px; BORDER-TOP: medium none; TOP: 1px; BORDER-RIGHT: medium none; LEFT: 315px">
<P>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer eget libero eget sem sagittis dignissim quis in orci. Praesent eget lacus nunc. Mauris id nibh tellus, nec pharetra nisi. Nulla dolor nunc, vulputate quis scelerisque sit amet, bibendum nec tortor. In bibendum ligula et velit lobortis vel lobortis odio adipiscing. Pellentesque habitant morbi tristique senectus</P></DIV></DIV>

But you can do other useful things with absolute addressing as well, such as lists. Here is a 'table' of block tags for list elements from Wikipedia, just to demonstrate

<dl>…</dl> A definition list (consisting of definition terms paired with definitions). DL existed in HTML Tags, and was standardised in HTML 2.0; still current.

<dt>…</dt>A definition term in a definition list. DT existed in HTML Tags, and was standardised in HTML 2.0; still current.

<dd>…</dd>The definition of a term, in a definition list. DD existed in HTML Tags, and was standardised in HTML 2.0; still current.

<ol>…</ol>An ordered (enumerated) list. The type attribute can be used to specify the kind of ordering, but stylesheets give more control: {list-style-type: foo}. The default is Arabic numbering. OL existed in HTML Internet Draft 1.2, and was standardised in HTML 2.0; still current.

<ul>…</ul>An unordered (bulleted) list. Stylesheets can be used to specify the list marker: {list-style-type: foo}. The default marker is a disc. UL existed in HTML Tags, and was standardised in HTML 2.0; still current.

<li>?</li> A list item in ordered (ol) or unordered (ul) lists. LI existed in HTML Tags, and was standardised in HTML 2.0; still current.

and the code for a single definition has very little overhead

<p><span class="subject">&lt;li&gt;?&lt;/li&gt;</span>
A list item in ordered (ol) or unordered (ul) lists.
LI existed in HTML Tags, and was standardised in HTML 2.0; still current.</p>

I could have achieved a certain virtue by redefining the <DL><DT><DD>directory list tags to get a similar effect, using floats, but you'll spot the fact that this will allow other effects such as side-notes and references. You'll see that the text in the left-hand column wll align, horizontally, with the line where the 'subject' element is placed. This can even be used for keeping illustrations tied to the text that they relate to.

12/ The order with which you define the styles in the stylesheet affects the appearance of the pages

If you have a number of similar styles, it is handy to style them all the same first and then style the differences further down in the stylesheet. You save a great mass of code that way. The problems happen if the order gets jumbled. If there are two contrary styles for the same attribute, the last definition gets precedence. Likewise, the order in which you define the pseudo-classes of the anchor elements will affect  the way that they work.  This is why you get advice to define them in the order link, visited, hover and active

So there is my dozen nuggets of advice that I'd pass on about using CSS. In general, when designing web pages, I reckon it is best to keep a good stock of designs that seem to work well, and copy those things that make them work well. There are very few people who can make a good website design: far, far, fewer than those who think they can, so learn from those who are obviously good. Use a CSS framework where possible, and mould it to your requirements.

I'm a believer in the idea that the layout of text on a web page is very little different from the old fashioned art of typography, and I keep a lot of printed publications, in a range of styles, around me to get inspiration from.  It prevents me from making elementary mistakes.

For sites to visit, I recommend

For reading material, I can recommend

William Brewer

Author profile:

William Brewer is a SQL Server developer who has worked as a Database consultant and Business Analyst for several Financial Services organisations in the City of London. True to his name, he is also an expert on real ale.

Search for other articles by William Brewer

Rate this article:   Avg rating: from a total of 58 votes.


Poor

OK

Good

Great

Must read
Have Your Say
Do you have an opinion on this article? Then add your comment below:
You must be logged in to post to this forum

Click here to log in.


Subject: Web Design
Posted by: Web development London (not signed in)
Posted on: Saturday, May 22, 2010 at 3:40 AM
Message: Your article is good! Generally when I read articles, I just come across nothing,
but this time I was really surprised when I got your article containing wonderful information.
Thanks mate and keep this effort up.
web development london

Subject: CSS Reset
Posted by: Derek (not signed in)
Posted on: Sunday, May 23, 2010 at 6:11 AM
Message: Hi,

I couldn't agree more on resetting the default settings so that fonts are the same in all browsers. I have used the Yahoo Reset (<a href='http://developer.yahoo.com/yui/reset/'>developer.yahoo.com/yui/reset/</a> on my site <a href='http://cheapflightstonz.com.au'>CheapFlightsToNZ.com.au</a>.

Subject: Good Stuff
Posted by: Damien (not signed in)
Posted on: Monday, May 24, 2010 at 5:33 PM
Message: Good read.

I really wish I'd read (and understood) some of these concepts 2 years ago. The absolute/relative stuff and CSS reset is gold.

Another similar one that I use is:

* {padding: 0; margin: 0;} /* Default zero out all margins to prevent cross-brower issues*/


Subject: Cruft
Posted by: ja (not signed in)
Posted on: Tuesday, May 25, 2010 at 9:10 AM
Message: <style type="text/CSS">
<!--
-->
</style>

What year is it again? 1995? You don't need the HTML comment cruft in there.

Subject: WHY ARE YOU YELLING?
Posted by: Jason (view profile)
Posted on: Wednesday, May 26, 2010 at 8:59 AM
Message: Turn off your caps lock, nothing makes me cringe more than seeing < CAPITALIZED MARKUP / >.

Subject: oh the irony
Posted by: Anonymous (not signed in)
Posted on: Wednesday, May 26, 2010 at 10:23 AM
Message: 11/ Relative and absolute addressing represent powerful magic.

This section is completely mangled (overlapping content) on Firefox 3.5.9 (Ubuntu 9.10)

css is cruel

Subject: css is cruel
Posted by: Anonymous (not signed in)
Posted on: Wednesday, May 26, 2010 at 10:24 AM
Message: oops... only with zoom on...

Subject: #9 attaching css to id in asp.net
Posted by: tlb (not signed in)
Posted on: Tuesday, June 1, 2010 at 12:02 PM
Message: If you are working in asp.net, #9 could get you into a lot of trouble. ASP.Net changes the id of elements that are to be accessed server side. So if you attach a style to an id and later a backend developer adds runat="server", it will change the id in the rendered code and any css that references that id will no longer work.

 

Top Rated

The Zen of Code Reviews: Best Practices
 If you don't feel that you are getting helpful and comprehensive feedback from code reviews, it may... Read more...

Improving Web Page Performance
 Visitors to a website are put off by having to wait for pages to load. Additionally, Google uses the... Read more...

Building a Customised ALM Platform with TFS and VSO
 The latest versions of Team Foundation Server are not only sophisticated, but extensible. Continue... Read more...

Acceptance Testing with FitNesse: Multiplicities and Comparisons
 FitNesse is one of the most popular tools for unit testing since it is designed with a Wiki-style... Read more...

Acceptance Testing with FitNesse: Documentation and Infrastructure
 FitNesse is a popular general-purpose wiki-based framework for writing acceptance tests for software... Read more...

Most Viewed

A Complete URL Rewriting Solution for ASP.NET 2.0
 Ever wondered whether it's possible to create neater URLS, free of bulky Query String parameters?... Read more...

Visual Studio Setup - projects and custom actions
 This article describes the kinds of custom actions that can be used in your Visual Studio setup project. Read more...

.NET Application Architecture: the Data Access Layer
 Find out how to design a robust data access layer for your .NET applications. Read more...

Calling Cross Domain Web Services in AJAX
 The latest craze for mashups involves making cross-domain calls to Web Services from APIs made publicly... Read more...

10 Reasons Why Visual Basic is Better Than C#
 After having converted a whole lot of training materials based on VB.NET into C#, Andy ‘Wise Owl’ Brown... Read more...

Why Join

Over 400,000 Microsoft professionals subscribe to the Simple-Talk technical journal. Join today, it's fast, simple, free and secure.