Looking for the lessons? Get started!
The definition and characteristics of CSS.
The entire Web Design Principles section can be accessed through the menu below.
Unfortunately, not everyone’s browser will support the spiffy JavaScript menu behind that innocent-looking button. If your browser won’t display the menu, just click on the button and you’ll be taken to a separate page with the entire menu displayed in clear, non-JavaScript HTML.
You affect the world by what you browse. — Tim Berners-Lee
CSS stands for “Cascading Style Sheet.” Like many, I write the word as “stylesheet” (one word, not two). I won’t get into the semantics of “stylesheet” vs. “style sheet.” You will see both in your travels around the Web.
According to a definition written by Maxine Sherrin and John Allsopp of Westciv:
A stylesheet is a set of instructions each of which tells a browser how to draw a particular element on a page. It’s very important to grasp this idea of HTML elements when you are working with CSS.
Web specialist Craig Grannell gives a longer take:
CSS is the W3C standard for defining the visual presentation for web pages. HTML was designed as a structural markup language, but the demands of users and designers encouraged browser manufacturers to support and develop presentation-oriented tags. These tags “polluted” HTML, pushing the language toward one of decorative style rather than logical structure. Its increasing complexity made life hard for web designers, and source code began to balloon for even basic presentation-oriented tasks. Along with creating needlessly large HTML files, things like font tags created web pages that weren’t consistent across browsers and platforms, and styles had to be applied to individual elements – a time-consuming process.
The concept behind CSS was simple, yet revolutionary: remove the presentation and separate design from content. Let HTML (and later XHTML) deal with structure, and use a separate CSS document for the application of visual presentation.
And author and Web designer Rachel Andrew writes:
The basic purpose of CSS is to allow the designer to define style declarations (formatting details such as fonts, element sizes, and colors), and to apply those styles to selected portions of HTML pages using selectors — references to an element or group of elements to which the style is applied.
Think about driving through a particular neighborhood. If all the homes were built by the same developer, you might see the same three or four house styles repeated over and over again. But each one has differences – different color schemes, different landscaping, shutters on the windows or a lack thereof, different kinds of roof shingling, bay windows or casement windows, myriad other differences. Think of the fundamental house structures as the HTML of a site, and the different stylings and “decorations” as the CSS. (Actually, this isn’t a great analogy – CSS can control much of a site’s structure, and it adds a lot more to a site’s final appearance and function than a paint job or a set of oak shutters does to a house. But it’s a bad starting point.)
Someone very knowledgeable wrote about CSS for Wikipedia. Roger Johannson of 456 Berea Street wrote a more in-depth article on the subject. Using their articles, and Andrew’s book The CSS Anthology, as guides for the content on this page, I can start by telling you that CSS describes the presentation semantics, or the look and formatting, of a Web page. Basically, if you want all your text to appear in the Georgia font, be 18 pixels in size, be centered in the page, and appear on a fuchsia background with dancing ponies livening up the proceedings, you can do just that with CSS. Or something else entirely/
Looking Backward to Move Forward
Sometimes it’s helpful to look backwards before we move forward.
Web developer Rob Glazebrook reminds us that the concept of stylesheets are actually older than the Web. Back in the day, “style sheets” were documents (sometimes a single sheet, sometimes a long, detailed pamphlet or notebook) circulated around a company that told employees what documents produced by the company should look like. They covered everything from typefaces used in the document to colors in the masthead and the placement of the logo. Glazebrook writes:
It was a way of maintaining consistency across a wide range of documents created by any number of writers. Though the production of the individual documents was disparate, they created a consistent, cohesive whole.
That’s important, because the same paradigm drives Web stylesheets.
Here’s an example of Then vs. Now, adapted from Wendy Peck’s Bare Bones, No Crap, CSS Text Control Primer. (I love it for the title alone.)
The Old Broke-Down Fogey Way of Controlling Presentation:
<p><font color="#ff0000" size="2" face="Verdana, Arial, Helvetica, sans-serif">Text ready for control.</font>
Yes, your browser will read this and style the paragraph appropriately. So what’s the problem?
Imagine having a dozen, or a hundred, such paragraphs on your page. Every one needs styling — some differently than others. When you make a change to one, you need to comb through the page, making the same change a dozen or a hundred times – and when you’re finished, you get to go through the process again on the next page in the site. And the next.
The New Hotness Way of Controlling Presentation (if by “new” you mean “since around 1998”)
The CSS p { font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 12px; color: #ff0000; } The HTML <p>Simple content text ready for control.</p>
Want to change the color of your dozens of paragraphs from #ff0000
to something else, say a nice light blue: #f0f8ff
? Easy, just change one line of CSS:
color: #f0f8ff;
Changes done, go have a cup of coffee. Peck observes:
No matter how fancy CSS may get, this is the basic principle. The real power, other than reducing the amount of code in each page dramatically, is the ability to change your mind because the control for the text and the text are in totally different places.
Separating Content and Structure from Presentation
The biggest reason why we have two separate entities — HTML and CSS — is to separate document structure and content from its presentation.
Johannson writes:
Structure consists of the mandatory parts of an HTML document plus the semantic and structured markup of its contents. Presentation is the style you give the content. In most cases presentation is about the way a document looks, but it can also affect how a document sounds – not everybody uses a graphical web browser. Separate structure from presentation as much as possible. Ideally you should end up with an HTML document which contains the structure and content, and a separate CSS file which contains everything that controls presentation. ... When an HTML element exists that has a structural meaning suitable for the part of the content that is being marked up, there is no reason to use anything else. In other words, do not use CSS to make an HTML element look like another HTML element, for instance by using a span element instead of an h1 element to mark up a heading. By using semantic HTML, you will make the different parts of a document meaningful to any web browser, be it the very latest graphical web browsers on a modern PC, an old web browser that doesn’t handle CSS, a text-based browser in a Unix shell, or assistive technology used by people with disabilities.
Wikipedia notes:
This separation can improve content accessibility, provide more flexibility and control in the specification of presentation characteristics, enable multiple pages to share formatting, and reduce complexity and repetition in the structural content …
Later in his document, Johannson notes quite accurately that for CSS to properly control the stylings and presentation of an HTML document, the HTML must be semantically accurate and well-formed. One cannot hide or override the flaws of the other.
Organized Stylesheets
As Web designers create more, and more complex, sites, they begin to learn how to organize their stylesheets to be more effective and efficient. Designers tend to find their own methods of organizing their CSS, but here’s one method you might find useful as a starter. It’s adapted from three separate methodologies, by Rob Glazebrook, Douglas Bowman, and Tom Fadial.
Here’s one method for divvying up your stylesheet:
- Reset
- Global Styles (body, paragraphs, lists, etc)
- Page Structure
- Heading
- Main Content
- Sidebar
- Footer
- Headings
- Text Styles
- Navigation
- Search
- Links
- Forms
- Comments
- Miscellaneous
Naturally, you will want to modify this to suit your own needs. Some designers, for example, don’t use resets in their stylesheets.
Instead of writing a page about CSS resets, I’ll just point you to my three-part article on resets as it was published on Six Revisions in December 2010. I’m inordinately proud of it.
The three authors above all have different approaches (Glazebrook’s is quite different from the other two; Rob Soule has yet another useful method, as does Andy Ford), so you might want to read all the cited articles and see if any of the particular methods appeals to you.
It’s also worth your time to take a look at Chris Coyier’s video screencast taking the viewer through how Coyier (and others) organize their CSS. Coyier notes that by using “multi-line formatting” (the method I’m demonstrating throughout the site), it's easier to view attributes, while the use of “single-line formatting” (one line per rule) makes it easier to view selectors. This is a short example of “single-line formatting”:
body {font-size: 0.8em; color: #f00; }
Different designers have different ways of highlighting the divisions in their CSS, but the divisions are always some form of comments.
Glazebrook’s method is as simple as it gets:
/* Navigation */
Here’s how I do it. It’s simple, straightforward, and it works for me (note the spaces above and below the comment):
/***Navigation***/
Bowman, one of the best-known designers in the field, says he sets his commented divisions off like so:
/* Navigation ------------------------------------------ */
Fadial's method is even more elaborate:
/* -----------------------------------*/ /* -------->>> NAVIGATION <<<---------*/ /* -----------------------------------*/
Bowman writes of his division styling:
This makes it fairly easy for me – or a client who takes over the files – to find certain rules, or to know which rules affect a relevant portion of the design. Even more importantly, this method of organization saves a lot of time when troubleshooting any style sheets I’ve written, especially for older projects where memory of how a project was built might be fading.
But all the organization in the world won’t help you find a particular CSS section without scrolling up and down. This can be frustrating, especially when you’re working on an older project (as Bowman noted above) that you don’t recall very well.
Thankfully, Bowman has provided us a method to help us find particular elements in our stylesheets. He calls them flags.
Using “Flags” to Help You Find Items in Your Stylesheet
Bowman’s technique is as simple as it is elegant.
You probably use the text search of whatever program you code in to find particular sections or elements in your code. Sometimes this can be frustrating, especially when you run into duplicate text strings or you’re hunting for a single code snippet (try searching for “p” and see how many times you get false positives before finding what you’re looking for).
Bowman uses the “equals” character – =
– to create “flags” within his code for search purposes. The equals character is perfect for this, because it has no semantic meaning in CSS, and thus is rarely used in CSS coding.
Using the equals character, he sets “flags” beside particular elements. Like so:
/* =Navigation ------------------------------------------ */
Now, he can do a text search for =Navigation (or just =Nav or even =nav, if your text search isn’t case-sensitive) and quickly find the section he wants, without having to perform multiple searches.
Using a "Master" CSS File
Some designers prefer to keep each section – global resets, navigation, links, etc – in separate CSS files. They then link their page to a “master CSS stylesheet” and use the @import
function to “import” each file into the master sheet.
More about importing stylesheets.
I can understand designers doing this, but I don’t advocate it, largely because of the well-documented slowness some users experience when their browsers are forced to import multiple stylesheets.
Writing CSS Shorthand
CSS stylesheets tend to become long, tedious, and hard to manage. There’s so many things to cover in a varied and sophisticated Web site; I’ve often seen sites whose stylesheet(s) are larger in file size than any of their pages.
While there’s only so much that can be done to counter this, one method to keep the files smaller and more manageable is to use CSS shorthand.
Note: The information on this page is cribbed primarily from articles by Roger Johansson, Dustin Diaz, and Rob Glazebrook.
Color Code Shorthand
We’ve discussed using shorthand for color hex codes in the Color page, but there’s no harm in discussing it here, too.
We learned the best way to present colors, in hexadecimal code (hex code). In our stylesheets, we set the codes by using a hash mark (#
, properly known as an “octothorpe”) and a six-digit “hex code” to identify the color.
When a hex code consists of three pairs of hex digits (which can include the letters a through f), you can leave out one digit from the pair. Thusly:
#000000
becomes
#000
The color
#ffffff
becomes
#fff
The color
#336699
becomes
#369
and
#ff22bb
becomes
#f2b
Not so tough.
Box Dimensions Shorthand
Again, we’ve referred (briefly) to this concept in the page on positioning, and the page on margins and padding.
Basically, any “box” element can be styled with margins, padding, and other properties. Those come with values of top, right, bottom, and left; those values must be cited in that selfsame order. We cited the TRouBLe mnemonic in the other pages; it helps you remember the top-right-bottom-left order. Johannson and Diaz both say that since the four properties go clockwise, it helps to envision a clock face with its hands set at 12 and then moving around the clock face – 3, 6, and 9.
You don’t always use all four values. Here’s the basic underlying syntax, as delineated by Johannson:
- property: value1;
- property: value1 value2;
- property: value1 value2 value3;
- property: value1 value2 value3 value4;
As Johannson reminds us, which sides of the box the values affect depends on how many values you specify. This is how it works:
- One value: all sides
- Two values: top and bottom, right and left
- Three values: top, right and left, bottom
- Four values: top, right, bottom, left
Let’s use the padding of an element as an example. If you want to pad all four of your sides with the same value, here’s how:
padding: 10px;
Now all four sides will have 10 pixels of padding.
If you want the top and bottom to have one padding value, and the right and left to have a different value, you can use two values:
padding: 10px 5px;
Now your top and bottom will have 10 pixels of padding, and your right and left sides will have 5 pixels of padding.
Want the right and left to have the same padding value, but your top and bottom to be different? Here’s how:
padding: 10px 5px 20px;
Your top has 10 pixels of padding, your sides have 5, and your bottom has a generous 20px.
You can even set four different values without resorting to padding-top
, padding-right
, and the other properties:
padding: 10px 5px 20px 15px;
Border Shorthand
The top-right-bottom-left order applies to borders, also, but the addition of width and color values adds a bit of complexity.
You can combine all three values in a border property with CSS shorthand, but you have to put them in the proper order.
If you want your border to have a 1px wide, solid, black border, you can easily combine the three into a single property:
border: 1px solid #000;
Make sure your border shorthand observes the following order:
border: width style color;
Technically, it shouldn’t matter what order you put your border values in, but some browsers get persnickety, and it’s best to follow the W3C specifications just to make sure someone’s browser doesn’t choke.
If you’re just setting a width to a border’s top, right, bottom, and/or left sides, the same principles apply as in the example above.
You can learn more about all things CSS shorthand from Chris Coyier’s video screencast on the subject.
Background Shorthand
You have five, count ’em five, background properties:
- background-color
- background-image
- background-repeat
- background-attachment
- background-position
Let’s say you want to use all five properties in your background selector. You can write out five tedious properties and their separate values, or you can compress them into one:
background: #f00 url(background.gif) no-repeat fixed 5 5;
This makes your background color red, implements a background image, does not let the image repeat, “fixes” the background image so it does not scroll with the page, and sets the starting position for the image 5 pixels from the very top and left of the page.
As with the example above, the order of the values shouldn’t matter, but with some browsers it does, so it’s best to observe this order:
background: color image repeat attachment position;
(Note: when you give two values for background-position, place both values together, and when you’re using length or percentage values, place the horizontal value first.)
Johannson notes that he usually uses the background shorthand just for a color or an image, which defaults the unused property to “transparent”.
background: #f00;
or
background: url(image.gif)
Font Shorthand
You have six font properties, as we’ve discussed on the fonts page:
- font-style
- font-variant
- font-weight
- font-size
- line-height
- font-family
You can combine them into one info-packed CSS selector:
font: italic small-caps bold 1em/140% "Lucida Grande",sans-serif;
where your font style is italic, your font variant is small caps, your font weight is bold, your size is 1em, your line-height is 140%, and your font is set to Lucida Grande with the usual fallback of sans-serif.
And, again, you should use the proper order, as cited above.
List Shorthand
Not much here. We’ve looked at lists elsewhere, but here’s one shorthand property you might find useful.
There are three kinds of list-style properties we use:
- list-style-type
- list-style-position
- list-style-image
The easiest and most common shorthand for lists is to combine everything into one, in order to make them disappear (and remove bullets and numbering from the lists):
list-style:none;
However, you have more options. Let’s say you want to keep the “list item markers” (the bullets or numbering) inside each list item, use an image instead of a list item marker, and use squares if the image isn’t available. Here’s the shorthand code:
list-style:square inside url(image.gif);
CSS Instead of Tables
One of the primary functions of CSS is to control the layout of a Web page. (My stylesheet for this site controls this page’s three-column, heading/footer layout, for example.) A lot of very good, and very capable, designers still use tables for laying out their sites. There are dozens of reasons why this is no longer viable in a modern, best practices-driven Web design world (one design firm, Chromatic, lays out 13 very good reasons, in some detail), but trust me, table-driven layouts are over and done with. When someone who seems knowledgeable about Web design advocates tables over CSS to you, ask them why they’re not running Windows 3.1 instead of their WinXP or Win7 on their computers — or why they’re not using an Apple Lisa instead of a Mac OSX.
Browser Support for CSS
Not all browsers support CSS’s most modern accepted form, CSS 2.1, completely. (CSS 3 is in development, and us design folks are all giddy about it, but it will be years before a majority of browsers implement its elements properly, so for now, let’s stick with CSS 2.1. That’s quite enough to deal with!)
As noted above, different browsers manage CSS (and HTML) with varying degrees of accuracy. None of them get it right 100% of the time, but some come very close. Browsers actually come in families, and the families each have their own strengths and weaknesses.
- The Gecko Family
- Includes Firefox, Camino, Flock, SeaMonkey, etc. Very, very good at handling CSS.
- Presto
- Opera is the only browser in this family. Also very strong at handling CSS.
- The Webkit Family
- Mac’s Safari and Google’s Chrome, along with OmniWeb, Shiira, iCab, and others are Webkit browsers, and all handle CSS quite well.
- The Trident Family
- Internet Explorer (the big dog in the yard), Maxthon, Sleipnir, NeoPlanet, and a few other browsers comprise this family of browsers. There’s always one dysfunctional crowd in the neighborhood, and this one is it. Microsoft claims that IE8 fully supports CSS 2.1. It doesn’t, though it’s much better than IE7, and light-years ahead of its predecessor, the almost hatefully deficient IE6. IE9 and IE10 do a pretty fair job of handling CSS 2.1, but there are some odd dropouts.
Because a majority of the world’s computer users surf the Web with some version of Internet Explorer, you have to design with IE’s flaws and bugs in mind. There is an entire cottage industry of designers who have documented and attempted to find fixes or “hacks” for a plethora of IE bugs. Sooner or later, you will find yourself making use of their work.
Some designers get snippy about supporting IE6 and other superseded, “obsolete” browsers. “Those people need to get with the new millennium,” they snap. “I would no more design for IE6 than I would build a car that burns leaded gasoline.” That’s their prerogative, but to my mind it’s exclusionary and wrong. Hundreds of thousands of Web users (at the least) rely on IE6 for their Internet needs, whether by choice (informed or not) or by necessity. To lock them out of your Web site because you think their browser is not serving the needs of your users.
Roger Johannson agrees, while acknowledging the limitations of designing for IE and other less functional browsers. He observes:
It’s important to stress that people using old (obsolete) browsers and browsers that by design do not support CSS must not be locked out. In the nineties, browser sniffing was a popular way of redirecting people using the “wrong” browser (normally anything but Internet Explorer for Windows) to a page that told them to upgrade their browser to gain access to the site. These days you can handle unsupported browsers in a better way. One big advantage of using logical, semantic HTML is that it makes documents accessible and usable even without CSS. The presentation – the way the document looks – won’t be the same as in a supported browser, but the content will be there. In most cases, for most visitors to a site, the content is actually more important than the way it is presented. That’s why it is better to send an unstyled page to unsupported browsers than to lock them out of the site.
Sending your less up-to-date users to an unstyled version of your site is a drastic solution, but sometimes necessary. More often, we can have the design “degrade,” presenting a less sophisticated version of our styling and presentation for the less capable browsers without losing functionality, elegance, or appeal.
There are, of course, other browsers out there. If it was made at some point in the dim and distant past, someone somewhere is using it (yes, even WebTV, which is now MSN TV). But there is the principle of diminishing returns. If 0.1% of your visitors are using Netscape 4, for example, why spend an inordinate amount of time and energy coding for that infinitesimal (and ever-shrinking) group of users? (Of course, your site’s particular audience might have an outsized number of users with that ancient browser, so in that case, you have to code for it.) On the other hand, half the world is moving to mobile devices – handhelds, cell phones, Blackberries, PDAs, iPads, and the like. If you’re not coding for them, you need to ask yourself why are you leaving them out? That’s why you need to learn to interpret your server logs, or a bit easier, implement and use Google Analytics for your site; learn your audience; and test, test, test your site in every browser you can think to use.