Tags: stylesheets



Monday, August 10th, 2020


Hidde gave a great talk recently called On the origin of cascades (by means of natural selectors):

It’s been 25 years since the first people proposed a language to style the web. Since the late nineties, CSS lived through years of platform evolution.

It’s a lovely history lesson that reminded me of that great post by Zach Bloom a while back called The Languages Which Almost Became CSS.

The TL;DR timeline of CSS goes something like this:

Håkon and Bert joined forces and that’s what led to the Cascading Style Sheet language we use today.

Hidde looks at how the concept of the cascade evolved from those early days. But there’s another idea in Håkon’s proposal that fascinates me:

While the author (or publisher) often wants to give the documents a distinct look and feel, the user will set preferences to make all documents appear more similar. Designing a style sheet notation that fill both groups’ needs is a challenge.

The proposed solution is referred to as “influence”.

The user supplies the initial sheet which may request total control of the presentation, but — more likely — hands most of the influence over to the style sheets referenced in the incoming document.

So an author could try demanding that their lovely styles are to be implemented without question by specifying an influence of 100%. The proposed syntax looked like this:

h1.font.size = 24pt 100%

More reasonably, the author could specify, say, 40% influence:

h2.font.size = 20pt 40%

Here, the requested influence is reduced to 40%. If a style sheet later in the cascade also requests influence over h2.font.size, up to 60% can be granted. When the document is rendered, a weighted average of the two requests is calculated, and the final font size is determined.

Okay, that sounds pretty convoluted but then again, so is specificity.

This idea of influence in CSS reminds me of Cap’s post about The Sliding Scale of Giving a Fuck:

Hold on a second. I’m like a two-out-of-ten on this. How strongly do you feel?

I’m probably a six-out-of-ten, I replied after a couple moments of consideration.

Cool, then let’s do it your way.

In the end, the concept of influence in CSS died out, but user style sheets survived …for a while. Now they too are as dead as a dodo. Most people today aren’t aware that browsers used to provide a mechanism for applying your own visual preferences for browsing the web (kind of like Neopets or MySpace but for literally every single web page …just think of how empowering that was!).

Even if you don’t mourn the death of user style sheets—you can dismiss them as a power-user feature—I think it’s such a shame that the concept of shared influence has fallen by the wayside. Web design today is dictatorial. Designers and developers issue their ultimata in the form of CSS, even though technically every line of CSS you write is a suggestion to a web browser—not a demand.

I wish that web design were more of a two-way street, more of a conversation between designer and end user.

There are occassional glimpses of this mindset. Like I said when I added a dark mode to my website:

Y’know, when I first heard about Apple adding dark mode to their OS—and also to CSS—I thought, “Oh, great, Apple are making shit up again!” But then I realised that, like user style sheets, this is one more reminder to designers and developers that they don’t get the last word—users do.

Friday, July 31st, 2020

On the origin of cascades

This is a great talk by Hidde, looking at the history and evolution of cascading style sheets. Right up my alley!

Sunday, January 13th, 2019

Code print

You know what I like? Print stylesheets!

I mean, I’m not a huge fan of trying to get the damn things to work consistently—thanks, browsers—but I love the fact that they exist (athough I’ve come across a worrying number of web developers who weren’t aware of their existence). Print stylesheets are one more example of the assumption-puncturing nature of the web: don’t assume that everyone will be reading your content on a screen. News articles, blog posts, recipes, lyrics …there are many situations where a well-considered print stylesheet can make all the difference to the overall experience.

You know what I don’t like? QR codes!

It’s not because they’re ugly, or because they’ve been over-used by the advertising industry in completely inapropriate ways. No, I don’t like QR codes because they aren’t an open standard. Still, I must grudgingly admit that they’re a convenient way of providing a shortcut to a URL (albeit a completely opaque one—you never know if it’s actually going to take you to the URL it promises or to a Rick Astley video). And now that the parsing of QR codes is built into iOS without the need for any additional application, the barrier to usage is lower than ever.

So much as I might grit my teeth, QR codes and print stylesheets make for good bedfellows.

I picked up a handy tip from a Smashing Magazine article about print stylesheets a few years back. You can the combination of a @media print and generated content to provide a QR code for the URL of the page being printed out. Google’s Chart API provides a really handy shortcut for generating QR codes:


Except that there’s no telling how long that will continue to work. Google being Google, they’ve deprecated the simple image chart API in favour of the over-engineered JavaScript alternative. So just as I recently had to migrate all my maps over to Leaflet when Google changed their Maps API from under the feet of developers, the clock is ticking on when I’ll have to find an alternative to the Image Charts API.

For now, I’ve got the QR code generation happening on The Session for individual discussions, events, recordings, sessions, and tunes. For the tunes, there’s also a separate URL for each setting of a tune, specifically for printing out. I’ve added a QR code there too.

Experimenting with print stylesheets and QR codes.

I’ve been thinking about another potential use for QR codes. I’m preparing a new talk for An Event Apart Seattle. The talk is going to be quite practical—for a change—and I’m going to be encouraging people to visit some URLs. It might be fun to include the biggest possible QR code on a slide.

I’d better generate the images before Google shuts down that API.

Saturday, November 10th, 2018

CSS and Network Performance – CSS Wizardry

Harry takes a look at the performance implications of loading CSS. To be clear, this is not about the performance of CSS selectors or ordering (which really doesn’t make any difference at this point), but rather it’s about the different ways of getting rid of as much render-blocking CSS as possible.

…a good rule of thumb to remember is that your page will only render as quickly as your slowest stylesheet.

Wednesday, May 2nd, 2018

A Guide To The State Of Print Stylesheets In 2018 — Smashing Magazine

Good advice on print styles from Rachel. The browser support situation is frustrating; I suspect it’s because the people working on browsers would rather get stuck in on shinier stuff.

Thursday, June 22nd, 2017

Oh No! Our Stylesheet Only Grows and Grows and Grows! (The Append-Only Stylesheet Problem) | CSS-Tricks

I think Chris is on to something here when he identifies one of the biggest issues with CSS growing out of control:

The developers are afraid of the CSS.

Thursday, April 20th, 2017

There are maps for these territories | Clearleft

A great piece from Danielle on the different mental models needed for different languages. When someone describes a language—like CSS—as “broken”, it may well be that there’s a mismatch in mental models.

CSS isn’t a programming language. It’s a stylesheet language. We shouldn’t expect it to behave like a programming language. It has its own unique landscape and structures, ones that people with programming language mental maps might not expect.

I believe that this mismatch of expectation is what has led to the current explosion of CSS-in-JS solutions. Confronted with a language that seems arbitrary and illogical, and having spent little or no time exposed to the landscape, developers dismiss CSS as ‘broken’ and use systems that either sweep it under the rug, or attempt to force it into alignment with the landscape of a programming language — often sacrificing some of the most powerful features of CSS.

Tuesday, April 4th, 2017

Jeremy Keith Interview

I had a chat with Toby Osbourn over Skype. He’s writing a book all about print stylesheets so that’s we talked about.

Monday, April 3rd, 2017

Cascading HTML Style Sheets — A Proposal

It’s fascinating to look back at this early proposal for CSS from 1994 and see what the syntax might have been:

A one-statement style sheet that sets the font size of the h1 element:

h1.font.size = 24pt 100%

The percentage at the end of the line indicates what degree of influence that is requested (here 100%).

Saturday, February 18th, 2017

Base64 Encoding & Performance, Part 1: What’s Up with Base64?

Harry clearly outlines the performance problems of Base64 encoding images in stylesheets. He’s got a follow-up post with sample data.

Saturday, October 29th, 2011

What’s slated for CSS4 Selectors? - destroy/dstorey

David gives a quick rundown of some of the selectors we can expect to see in CSS4.

Thursday, January 7th, 2010


This is an interesting idea: paste in some markup and this will automatically generate CSS selectors based on your classes and IDs.

Monday, October 5th, 2009

printFancy, a gallery of websites in print

A CSS gallery with a difference. This one highlights sites with good print stylesheets.

Thursday, December 6th, 2007

Vitamin Features » Creating Sexy Stylesheets

Jina has put together an excellent series of steps you can take to keep not just nice, but downright sexy.

Sunday, April 29th, 2007

110am. A Seasonal Design

Tom Watson's new site design changes stylesheets with the season. More of this kind of thing please, Web.

Tuesday, April 25th, 2006

Print stylesheets

CSS Naked Day was fun. It felt almost voyeuristic to peek under the CSS skirts of so many sites. It also made me realise that the browser default styles are what people are going to see if they decide to print out a page from many CSS-based sites.

I’ve had a rudimentary print stylesheet in place for Adactio for a while now, although I should probably revisit it and tweak it some time. But a lot of other sites that I’ve designed have been woefully lacking in print stylesheets.

For instance, the situation with the DOM Scripting site was brought home to me when I received this message from Adam Messinger:

Would it be possible to get a print stylesheet for the errata page that does a better job of preserving the table layout? As it is now, it’s sometimes hard to tell which page numbers match up to what errors. Just some borders on the table would help a lot.

That one made me slap my forehead. Of course! If ever there was a web page that was likely to be printed out, the errata for a printed book would be it.

As well as adding borders to the errata table, I set to work on creating a stylesheet for the whole site. It was fairly quickly and painless. I hid the navigation, let the content flow into one column, set the font sizes in points and used a minimum amount of colour.

DOM Scripting blog on screen DOM Scripting blog in print

I did much the same for Jessica’s site, WordRidden.

WordRidden on screen WordRidden in print

Principia Gastronomica was crying out for a print stylesheet. Half of the entries on that blog are recipes. Most people don’t have computer screens in their kitchens so it’s very likely that the recipes will be printed out.

A lot of the entries on Principia Gastronomica make heavy use of images. Everyone likes pictures of food, after all. I was faced with the question of whether or not to include these images in the printed versions.

In the end, I decided not to include the images. Firstly, it’s a real pain trying to ensure that the images don’t get split over two pages (page-break-before would be a draconian and wasteful solution). Secondly, I bowed to Jessica’s wisdom and experience in this matter. She often prints out recipes from sites like Epicurious and, when she does, she wants just the facts. Also, these are pages that are likely to printed out in the home, probably on a basic inkjet printer, rather than in an office equipped with a nice laser printer.

Principia Gastronomica on screen Principia Gastronomica in print

If you’re implementing a print stylesheet for your site, I highly recommend reading Richard’s guide, The Elements of Typographic Style Applied to the Web. All the advice is good for screen styles, but is especially applicable to print.

These articles on A List Apart are also required reading:

In an interview over on Vitamin, Eric makes the point that context is everything when deciding which stylesheets to serve up. Clearly, articles on a A List Apart are likely to printed out to be read, but the front page is more likely to be printed out to get a hard copy of the design.

For a detailed anatomy of a print stylesheet, be sure to read the latest in Mark’s Five Simple Steps to Typesetting on the web series: Printing the web.

Wednesday, April 5th, 2006


My site has no stylesheets (“how does it smell?”, etc.) but you probably won’t even notice because chances are your reading this in a feedreader.

In any case, it’s nice just to look at the flow of the document sans styles. Notice the “More information” h2 tag that is normally hidden from view. With styles enabled, the visual layout makes this heading redundant but without styles, or for non-visual user-agents, it’s a useful marker.

The man responsible for this CSS nakedness is Dustin Diaz, himself no stranger to nudity.

I had a pleasant chat with Dustin yesterday which forms the basis for the latest episode of his podcast. It was fun for me. I don’t know how much fun it’ll be to listen back to. I ramble on about JavaScript, comments, food blogging and George Clooney. Listen for yourself.

Wednesday, January 11th, 2006

iIR: img Image Replacement

Aaron uses image replacement on an image to provide one image for screen and another print. Very clever.

Sunday, April 3rd, 2005

7 steps to better handheld browsing

Simon has some good hands-on suggestions for mobile stylesheets.

Tuesday, September 23rd, 2003

CSS Based Design

Let me tell you why you’re here. You’re here because you know something. What you know you can’t explain but you feel it, that there’s something wrong with the web.

Let me tell you why you’re here. You’re here because you know something. What you know you can’t explain but you feel it, that there’s something wrong with the web. You don’t know what it is but it’s there like a splinter in your mind driving you mad.

You can see it when you look out your browser window or when you turn on your web tv. You can feel it when you go to work, when you go to church, when you pay your taxes.

This is the web that you know. The web as it was at the end of the twentieth century.

This is the web as it exists today…

Welcome To The Desert Of The Web

<table border=0 width=100% cellspacing=0 cellpadding=0>
<td width=100%>
<table width=100% border=0 cellspacing=0 cellpadding=0 vspace=0>
<td valign=bottom><font size=2><br></font>
<table cellpadding="5" cellspacing="0" border="0" width="203" >
<tr><td height="105" valign="top">
<table width=610 cellpadding=0 cellspacing=0 border=0><tr><td width=1><spacer type=block width=1 height=1></td><td width=608 bgcolor=666666 height=1><spacer type=block width=1 height=1></td><td width=1><spacer type=block width=1 height=1></td></tr><tr><td width=1 bgcolor=666666><spacer type=block width=1 height=1></td><td><table width=100% cellpadding=0 cellspacing=0 border=0 bgcolor=e6e6e6><tr><td>
<td width="179" bgcolor="#ffffff" align="left">
<table width="179">
<tr><td><img src="http://pics.ebay.com/aw/pics/x.gif" height="0" width="0"></td></tr>
<tr valign="bottom">
<td valign="bottom" align="left" width="179" height="21">
<table align="left" width="157" cellpadding="0" cellspacing="0" border="0" bgcolor="#ffcc00">
<td align="left" colspan="2"><img src="http://pics.ebay.com/aw/pics/x.gif" width="157" height="2"></td>
<td align="right" rowspan="3" colspan="2"><img src= "http://pics.ebay.com/aw/pics/22x21.gif"
width="22" height="21" border="0"></td>

I didn’t say it would be easy. I just said it would be the truth.

Why Use XHTML?

Web development is a war and we are soldiers, writing hacks and workarounds to make designs look right in buggy older browsers.

What if tomorrow the war could be over? What if we could build sites that won’t fall apart in future browser releases? Isn’t that worth fighting for? Isn’t that worth developing for?

XHTML encourages good practice. All your markup will be well-formed and all your tags will be closed. This makes page rendering easier for browsers and it makes bug-tracking easier for you.

Best of all, using XHTML means that you must keep your presentation separate from your content.

All you have to do is free your mind.

Why Use CSS?

Just imagine all the benefits that come with separating your presentation from your content.

Your pages will be smaller, much smaller. Without the bloat that comes with nested tables, spacer images and font tags, your mark-up will be leaner and meaner. That will appeal to search engines.

Life will be simpler for the people in charge of the design: the presentation of an entire site full of documents can be changed by altering just one file without ever touching the content.

Life will also be simpler for the people in charge of the content: your mark-up will be human readable allowing the content to be updated without changing the rules that govern the presentation.

With Cascading Style Sheets, your content will be accessible to all browsing devices, past and present. That means everything from Lynx to web-enabled mobile devices and fridges.

Remember, all I’m offering is the truth - nothing more.

Where To Begin?

Okay, I’ll try to stop with the Matrix-speak and get down to business.

Where should you start when you want to create a CSS based design?

"Content Is King". It’s a pithy old adage but it’s true.

Everything begins with the content. Everything else is layered on top.

Your finished page will have layers of presentation piled one on top of the other. But if you peel those layers away, what you are left with is the very heart of your page: the content.

Standards compliant browsers will see a beautiful many-layered page. Browsers with partial CSS support will see a partially layered page. Older browsers and search engine robots won’t see the layers of presentation but they will see the page.

The process of adding these layers is called progressive enhancement.

The result of allowing those layers to be stripped away without affecting your content is called graceful degradation.

The first and most important step on the road to CSS based design is having semantically correct mark-up.

That’s just a fancy term for describing your content correctly.

Semantically Correct Mark-up

Put headings and subheadings into <h*> tags, <h1>, <h2>, <h3>, etc.

If a piece of text acts a label for an <input> item in a <form>, then describe it as such by using the <label> tag.

Wrap your paragraphs in <p> tags. If you have a list of links, then put them in a list (<ul> or <ol>) and make each of them a list item, <li>.

You may have pre-conceived notions about how these will look.

The default presentation of tags is a result of browsers following basic rules.

What you must learn is that these rules are no different than the rules of a computer system. Some of them can be bent. Others can be broken.

You think that all <li> list items appear vertically with a bullet point next to them? You think that’s air you’re breathing now?

Free. Your. Mind.

I’m sorry. That was the last Matrix reference: I promise.

<div> and <span>

Sometimes you’ll want to describe some content but there won’t be a suitable tag available. You can’t make up your own tags but you can reach for <div> and <span>.

A <div> is a block level element. That means it’s self-contained and comes with a built-in line break.

A <span> is an inline element. Inline elements don’t include a line break and must be contained within a block level element.

Both <div> and <span> are like blank slates just waiting for styles to be applied to them.

Don’t go overboard with <div> and <span>. If there’s an existing tag that describes your piece of content correctly then use that tag.

Classes and IDs

If you want to apply a style to all instances of a certain tag, then you simply reference that tag in your stylesheet.

If, on the other hand, you want to apply a style selectively, then you’re going to need to add either a class or an ID to the tag.

Classes are reusable. A document can contain any number of tags that use the same class, e.g.:
<p class="myclass">

An ID is unique. A document can only contain one instance of <p id="myid">.

Even though we can name our classes and IDs anything we wish, it’s still a good idea to try to use descriptive rather than visual terms. Describe a class as being "important" rather than "bigredbold".

If we combine the power of <div>s and IDs, we can take the semantic description of our documents even further than the tags provided by XHTML allow.

Most web pages can be divided up into sections like "main navigation", "sub navigation", "main content" "related material", etc.

XHTML doesn’t give us the tags to describe these chunks of content. But if we take the blank slate block-level tag (<div>) and give each section a unique identifier (ID), then we’ve taken semantic description to the next level.

If you mark up your pages with areas like <div id="branding">, <div id="footer">, etc. then you have a way to reference those chunks of content. You will then be able to affect their visual appearance and even change how they are positioned.

Applying Styles

If you’ve followed the advice I’ve given you so far then what you have now is a semantically correct document with no superfluous tags or attributes, broken down into helpful chunks.

Now we can begin to add the layers of presentation. We already have the core.

Inline styles

It’s possible to embed your styles within the very tags themselves e.g.:
<p style="text-align: right;">

But what’s the point of that? We want to separate presentation from content, not mix them up.

The <style> tag

We can give a document its styling instructions from within the <head> tag by wrapping everything up in <style></style> tags.

This is slightly better than inline styles but it still means our content and our presentation are in the same place.

External Stylesheets

By keeping our styles in external documents we achieve a true separation of content and presentation. We can also change the presentation applied to a multitude of documents by altering just one external file.

The easiest way to reference an external stylesheet is by using the <link> tag within the <head> of your document, like this:

<link rel="stylesheet" type="text/css" media="screen" href="path/to/stylesheet.css" />

Notice that there is an attribute called "media" which we have set to "screen". This means that the styles in that stylesheet will only be applied to on-screen presentation. We could use a different stylesheet entirely for printing out our documents, referenced with the "media" attribute set to "print".

The <link> tag is the most universally recognised way of referencing an external stylesheet. Even older browsers with just partial CSS support understand it.

Standards compliant browsers also understand the @import method of referencing stylesheets. We can use this to our advantage. We can provide a basic stylesheet with the simplest of instructions referenced by <link>. We can then add more complex instructions in stylesheets referenced by @import like this:

@import url("path/to/stylesheet.css");

Like the <link> method, we can put our @import command within the <head> of our document (nested in <style></style> tags). However, there’s a much cleverer way of referencing our more complex stylesheets.

We can put our @import command within the basic stylesheet that we referenced using <link>. That means our document only ever references one external stylesheet, a very basic one, but that stylesheet itself references more complex instructions.

Stylesheets within stylesheets. Basic styles for basic browsers. Complex styles for more complex browsers.

Once again, we’ve taken separation to another level. Now our stylesheets have been separated into basic styles and complex styles. We can go even further than this. To make life easier for us, we can have separate stylesheets for typography, positioning, etc., nested like russian dolls, one stylesheet referencing the next.


In our basic stylesheet, the one we reference with <link>, we can put simple information like the basic colours and fonts we want to use.

We start by referencing the <body> tag. Here’s how we specify the font-family we want to be used:

body {
 font-family: "Verdana", "Arial", "Helvetica", sans-serif;

Notice how we can specify different fonts in order of preferences. We want to use Verdana. Failing that, Arial. If Arial isn’t installed, then Helvetica will do. Finally, if none of those fonts are installed, then we say that any sans-serif font will do.


Now we can add some basic colour information. Whenever you specify the colour of something, it’s always a good idea to also specify the background colour.

We could use colour keywords like "white", "black", etc. but they’re fairly limited. We get a wider a range of values by using RGB values like #ffffff, #000000, etc.

Using web-safe RGB values also allows you to use a shorthand method of writing out the values. Instead of writing #6699cc, we can just write #69c.

Here’s how we’d add to our existing styles for the <body> tag to specify black text on a white background:

body {
 font-family: "Verdana", "Arial", "Helvetica", sans-serif;
 color: #000;
 background-color: #fff;


Now that we’ve set the typeface and colour for our document, let’s just take care of our links.

We can style our links to look however we want; bold, italic, underlined, whatever. We can also specify different styles for the various possible link states: link, visited, hover and active. These are called pseudo-classes.

 color: #f93;
 background-color: #fff;
 color: #c93;
 background-color: #fff;
 color: #fc6;
 background-color: #fff;
 color: #f96;
 background-color: #fff;

That’s the right order to specify the pseudo-classes. Here’s a handy mnemonic for remembering the order: LoVe HAte.

Sizes and Units

Whenever we specify the size of something using CSS, we have a number of different options open to us.

When sizing text, for example, we can use percentage values, pixels, points or ems. We can say font-size: 15px, font-size: 120%, font-size: 12pt or font-size: 1.5em. The important thing is that we always specify units of some sort.

Layering The Presentation

Once we have our basic typography and colour laid down and referenced via <link>, we can begin to add more complex styles referenced via @import.

CSS allows us to add typographic flourishes that were previously impossible to achieve on the web. Print designers will tell you how important leading and kerning are when laying out text on a page. The CSS equivalent to leading is line-height. For kerning we use letter-spacing:

.ourclass {
 letter-spacing: 0.5em;
 line-height: 150%;

Another handy feature of CSS is the ability to add a background image to any element.

body {
 background-image: url("path/to/image.file");

We can also control the amount and direction of tiling we want from the background image. This is done using background-repeat. If we don’t want the background image to tile at all, we give this a value of none. If we want it to tile vertically but not horizontally, we give background-repeat a value of repeat-y.

body {
 background-image: url("path/to/image.file");
 background-repeat: repeat-y;

We can also position the background image so it need not necessarily begin in the top left corner of its containing element (the default position for background images). To do this we use background-position and we can specify either keywords, e.g. top, right, etc. or we can use units like pixels or percentages. We can even mix units.

body {
 background-image: url("path/to/image.file");
 background-repeat: repeat-y;
 background-position: 90% 25px;

The Box Model

Every element has an invisible box around it. The content of every element is surrounded by padding. This padding is contained by a border. The border is surrounded by a margin.

The box model: content surrounded by padding, surrounded by border, surrounded by margin

We can manipulate the values of all three of these properties. For instance, we can change the width, style and colour of the border:

 border-width: 2px;
 border-style: dotted;
 border-color: #000;

Or we can combine these all together with this shorthand notation:

 border: 2px dotted #000;

For padding and margin we can specify the width for all four sides. Again, we are free to use any units we want and we can mix units.

If you are wondering whether to increase the padding or the margin of an element in order to add space around it, just remember that the padding extends right up to the border and will inherit values from the element itself such as background-color. The margin on the other hand, begins outside the border and doesn’t inherit values from inside the border.

Here’s one way to specify all four margin values of an element:

 margin-top: 20px;
 margin-right: 10px;
 margin-bottom: 20px;
 margin-left: 10px;

Or we could use this shorthand notation, going clockwise from the top:

 margin: 20px 10px 20px 10px;

In this case, because the top and bottom values are the same and the the left and right values are the same, we can use even more shorthand and just specify the vertical and horizontal values:

 margin: 20px 10px;

If we wanted the same value on all four sides, all we’d have to declare is:

 margin: 20px;

Many elements have inherent values for margin: it’s what determines between the space between paragraphs or the distance between the edge of the screen and where the <body> begins. We can still manipulate these values. So if you wanted no space between the edge of the screen and the beginning of the <body>, simply declare:

body {
 margin: 0;

You’ve probably noticed that I didn’t specify any units there. Didn’t I say that you should always specify units? Well, there’s one exception to that and that’s when the value you’re giving is zero. Zero pixels is the same as zero percent is the same as zero points.

Adding It All Up

One of the most obvious ways of manipulating an element’s appearance is to change its size. We do this by altering its width and/or height. Once again, we are free to use any units we wish:

 width: 50%;
 height: 100px;

So what happens when we declare an element’s size but we also declare sizes for its padding, border and margin?

 width: 200px
 padding: 10px;
 border: 10px;
 margin: 10px;

In theory, all of these values are added together to give the total width:

 200 (width)
+ 10 (left padding)
+ 10 (right padding)
+ 10 (left border)
+ 10 (right border)
+ 10 (left margin)
+ 10 (right margin)
 260 pixels total width

Unfortunately, the Windows version of Internet Explorer 5 (and, depending on your doctype, IE6) gets it wrong.

Internet Explorer gives the overall total width at 220 pixels. The actual content of the element is reduced to 160 pixels because of the application of padding and border. Only the margin values are correctly applied.

You’ll need to bear this discrepancy in mind when you’re putting together CSS designs but there are workarounds to get around this.


CSS allows us not only to change the appearance of page elements. With block-level elements we can also affect where they appear in the page. This is done using the position declaration together with declarations like top, left, bottom and right.

Again, you can use any units you like, though pixels are probably your safest bet.

By default, all page elements have a position of static which simply means that they appear where they would normally appear anyway, without any CSS trickery applied. When we want to manipulate the position of an element, such as a <div>, then the two most important positioning options available to us are relative and absolute.


Using position: relative, declarations like top and left refer to the element’s normal (static) position in the document:

 position: relative;
 top: 10px;
 left: 10px;

This would put an element ten pixels below and to the right of where it would normally be.


Using position: absolute, declarations like top and left refer to the containing element. In most cases, this would be the <body>:

 position: absolute;
 top: 10px;
 left: 10px;

This would put an element ten pixels below and to the right of the top left corner of the screen.

Once you declare that an element has a position that is absolute, that element is taken out of the flow of the document. Its default position is no longer where it would normally appear. Instead, its default position is the top left corner of its containing element (usually the <body>).

In other words, the order of absolutely positioned elements in the XHTML document no longer matters. Their positions now depend entirely on the CSS. Your document could have <div id="content"> followed by <div id="navigation"> but you could use CSS to place the navigation before the content.

Absolute positioning allows for pixel-perfect designs to be realised although it is more suited to "fixed" rather than "liquid" designs. It also forms the basis of DHTML animation. DHTML is simply the combination of HTML, CSS and Javascript (styles applied to HTML elements can be manipulated with Javascript).


Absolutely positioning elements is all well and good when you know the exact size of each element and the exact position where you want them to appear. It can’t help you if you want the position of one element to depend on the position of another.

You might want to declare, for instance, "whatever follows this element should appear to the right of it". Because absolutely positioned elements are taken out of the document flow, they have no context to relate to.

Luckily, we have the very powerful float declaration which is all about context.

As we have seen, all block-level elements have an in-built line break. A series of block-level elements, such as <div>s appear one underneath the other.

By applying a float declaration of left or right, we can determine what happens to the element that follows. Instead of appearing underneath its preceding element, it butts against it.

For the following examples, let’s assume that each box is a <div> of fixed width and height.

Let’s apply float: left to box number one:

three boxes, two on the first row, one on the second

Box number two butts against the right of box number one.

Now let’s apply float: left to boxes one and two:

three boxes, all in a row

Box number two butts against the right of box number one and box number three butts up to the right of box number two.

We are also provided with an antidote to float. It’s called clear. By applying a clear declaration of left, right or both, we can "break out" of any abutting caused by preceding elements.

Let’s apply clear: left to box number three:

three boxes, two on the first row, one on the second

Even though box number two has a float: left declaration, box number three appears below it instead of butting against it. By declaring clear: left on box number three, we can be sure that nothing will appear to the left of it.

Here’s a fairly complicated arrangement:

three boxes, two on the first row, separated by a gap, with one box on the second row

We’ve declared float: left on box number one so anything following it should butt against its right side. However, it’s followed by box number two which has float: right declared so it appears off to the right hand side. Anything following box number two should butt against its left side. However, in this case the following element, box number three has a clear: both declaration so it doesn’t appear to the left or right of anything.


Putting It All Together

Now you’ve seen just some of the things of which CSS is capable. There are many more stylesheet declarations that I haven’t covered but we’ve seen the most important cornerstones.

  1. Begin with correctly marked up XHTML documents.
  2. Add basic styles with a stylesheet referenced with the <link> tag.
  3. Use @import to reference stylesheets with more complex declarations.
  4. Position page elements either absolutely or relatively.

If you build your websites this way, the rewards will be manifold:

  • Faster loading times: stripping out <font> and <table> tags can bring page sizes down enormously.
  • Backwards compatibility: even the oldest web browser will be able to access your content.
  • Better search engine rankings: Google loves semantically correct documents and hates tag soup. Clever Google.
  • Ease of updates: you’ll be able to update your content without worry of changing your design and you’ll be able to change your design by just changing one or two files.

Welcome… to the real web