Get started with CSS

Designing with standards

Get to know standardized CSS styling techniques, including CSS 2.1 and the cross-browser CSS3. In particular, learn how to enhance search engine optimization using unobtrusive techniques; provide different CSS styles for print, mobile, and web views; and hint toward enhanced accessibility.

Daniel J Lewis, Computer Scientist, Vanir Systems

Daniel LewisDaniel John Lewis is freelance computer scientist from England and the son of a graphics/colour design expert. He develops web applications in a variety of languages (including PHP, Ruby, Java, and XHTML) and has been using development and design software since the late 1980s. His computer science research and consultancy tends to be in the areas of Semantic Web, linked data, artificial intelligence, machine learning, data mining, and "computation for humanities." You can reach Daniel at daniel@vanirsystems.com.



10 May 2011

Also available in Chinese Japanese

Develop skills on this topic

This content is part of a progressive knowledge path for advancing your skills. See Get started with Dojo development

Cascading style sheets are, quite simply, the design layered over the top of an (X)HTML web page. What makes the style sheet "cascading" is that you can apply it across the site—that is, you apply the style to the website, and it applies itself throughout each element of each page.

For websites, it is an important concept to separate data from design: The data is sent to the browser using (X)HTML, and the design is applied to that data using CSS. This separation allows people to render a web page without your design if they have special accessibility needs and also allows machines (such as search engines) to index a website without design "getting in the way."

Frequently used acronyms

  • API: Application programming interface
  • CSS: Cascading style sheet
  • HTML: Hypertext Markup Language
  • XHTML: Extensible HTML

This article details various pre-existing and modern CSS techniques to enhance a website's look and feel. This article presumes some knowledge of (X)HTML, and it should be treated as a reference point for development, acting as an initial platform for designing websites.

The format of CSS

The structure of a CSS style element is simple:

html-tag-name {
	css-property-key-1: css-value-1;
	css-property-key-2: css-value-2;
}

Where html-tag-name could be any of the tags you would find in HTML code (for example, <a>, <div>, <li>, or <label>). Instead of an HTML tag, it could also be either an ID reference displayed with a preceding hash symbol (#) in CSS code, as shown here:

#id-of-html-tag {
	…
}

Or, the tag can be a class reference displayed with a preceding dot/period (.) symbol in CSS code:

.class-of-html-tag {
	…
}

These parts of CSS (html-tag-name, id-of-html-tag, or class-of-html-tag) are known as simple selectors and could be nested (with a space between) for increasing your granularity into HTML, as shown here:

outer-html-tag-name inner-html-tag-name { … }

Or used as a list for applying one design element to many selectors:

1st-html-tag-name, 2nd-html-tag-name { … }

Granted, the above code is quite an abstract way of understanding the formal syntax of CSS, so the rest of this article focuses on more concrete and useful examples that highlight the simplicity, potency, and flexibility of CSS.


Base styles

One of the first things to do when making a site design is establish the base style. You do so by styling the <body> tag, as Listing 1 shows.

Listing 1. CSS base style for the body tag
body{
background-color: #EEEEEE;
color: #000000;
margin: 0;
padding: 0;
text-align: left;
font-size: 100%;
  	font-family: sans-serif;
}

This markup makes the background color off-white (background-color), ensuring that the font color is black (color). It also ensures that all content edges match the edge of the browser window frame (margin and padding), and the markup horizontally aligns the textual content to the left (text-align). Finally, the style sets the font size to the browser default (font-size) and uses a sans-serif (that is, a font without the little flicks around the edges) font family (font-family).

These are, of course, simple settings. Generally, the following guidelines can be applied:

  • Where a colour is specified, use Red-Green-Blue (RGB) hexadecimal light values.
  • Where a size is specified, use pixels (indicated by a px after the number), an em (indicated by em after the number)—that is, the size of the font multiplied by the specified number—or a percentage (indicated by a % after the number).
  • Text can be aligned left, right, or center. Floats can also be left or right. Vertical alignments must be top, middle, or bottom.
  • Fonts can be any specific font or font family (serif, sans-serif, or monospace) or a downloadable font.

One of the most important decisions when determining the design of your website is whether to use a fluid or fixed layout. A fixed layout is one in which you specify the heights and widths of elements, and those values are the same no matter the operating system or browser with which you view the website. You specify these elements mostly using pixels. A fluid layout is one in which the heights and widths of elements are flexible and expand or contract based on the browser window, the operating system, and user preferences. You specify these elements mostly using percentages and ems. There are pros and cons for both fluid and fixed layouts, and which layout you choose depends on the type of content, the amount of content, and the audience the website receives.


Applying CSS to (X)HTML

To start applying your CSS, you need to tell the browser where to look for it. This should be the only true point where (X)HTML references CSS. You make the reference in either of two ways: the "quick and dirty" <style> tag or the unobtrusive "quick and clean" <link> tag.

Quick and dirty: the style tag

This method tends to be the quickest way to see your style applied to one web page, and it "dirties" the page with non-HTML code. However, it is just one web page that you apply the style to (unless, of course, you are using a server-side language to include a header), and if you copy and paste this style on each page, you increase the page size (I'm talking kilobytes here rather than width and height). Therefore, you increase the load time of each page, making the user wait. Time is a lot more crucial to the user than people imagine, even if you're living in a super-speed Internet age.

So how is it done? Quite simply, by adding the following markup to your HTML <head> tag:

<style>
	/** Your CSS goes here **/
</style>

Quick and clean: linking to a CSS unobtrusively

This method tends to be the cleaner way to apply your styles. When you have the CSS in an external file, you can link to it from other pages, thereby ensuring that you have clean HTML and smaller page sizes (once again, kilobytes rather than width and height). Using this method is even simpler: You add the following to your HTML <head> tag section:

<link href="http://www.example.com/styles/style.css" media="screen" 
        rel="stylesheet" type="text/css" />

Where style.css is a plain-text file with your CSS code inside. As good practice, I use the following base structure for my website's public html folder:

  • /. public html folder, containing HTML files or server-side scripts (such as PHP)
  • /index.html (or index.php for PHP development) for a home/start page
  • /styles/ directory for storing various CSS files
  • /scripts/ directory for storing various JavaScript files and libraries

This structure allows everything to be neatly packaged—while being kept separate and allowing it to be referenced.


Guide to styling

This section includes details on what happens if you apply CSS version 3 (CSS3) when that version isn't supported by a browser—that is, the browser will ignore it and regress to a default. This section also outlines browser-specific implementations of CSS3 styles (those beginning with -moz, -webkit, and the like).

A simple <div> tag

(X)HTML has the rather simple tag <div>, which you essentially use to section a web page into meaningful areas. From a design perspective, it is a nice idea, as it is essentially a box around your content.

Standard <div> effects with CSS 2.1

CSS has always had support for styling <div>s. Some of these elements include border adjustments such as:

border: size type color

Where:

  • size is a numeric value.
  • type is solid, dashed, dotted, double, or a few 3D-style borders.
  • color is usually an RGB hexadecimal value.

So for example, you can have border: 1px solid #000000; for a solid black line that is one pixel wide.

Like the body, you can also change the standard background colors and the font and colors of text. You make these changes just as you did in the base style.

Enhanced <div> effects with CSS3

One of the most requested pieces of design, not found in CSS2.1, was rounded edges to borders. This meant that a lot of designers in the past had to build image-based borders or use some dirty techniques combining CSS and JavaScript. Fortunately, this is no longer the case in CSS3, which introduces the border-radius property (for example, border-radius: 10px;).

To get this property to work in some browsers, you must include markup similar to this:

-webkit-border-radius: 10px;
-moz-border-radius: 10px;
border-radius: 10px;

This example is just so that the markup works with older Mozilla-based (such as Mozilla Firefox) and Webkit-based (such as Apple Safari) browsers. If you wish, you could set the above three properties to different values and have the style appear different in, for example, Firefox and Google Chrome.

There is also the ability to produce a shadow on a <div>. To do so, you use the following three properties (once again, dealing with various browsers):

-webkit-box-shadow: 8px 8px 6px #AAAAAA;
-moz-box-shadow: 8px 8px 6px #AAAAAA;
box-shadow: 8px 8px 6px #AAAAAA;

Where in this case, the first property is the horizontal shadow, the second is the vertical shadow, and the third is the amount of blur. The forth property is the colour of the shadow. You could place another property between the blur and the shadow—another size-based value related to the spread of shadow—but this does not seem to be widely used.

Lists

Another common element in (X)HTML is a list. Lists come in two forms: the unordered list (<ul>) and the ordered list (<ol>). These are useful for providing web pages with numeric lists, such as for procedural steps, and non-numeric lists, such as recipe ingredients. In terms of site layout, lists are often crucial to the development of site navigation structures and are, therefore, particularly useful to style.

An (X)HTML list, whether ordered or unordered, will by default have what is known as a list marker. In informal English, we would probably call them "bullet points." CSS2.1 has a small variety of list markers that you set using the list-style-type property. The usual values for unordered list markers are none, disc, circle, and square.

Values for ordered list markers are based on how the numbers are represented. The most-used options are decimal, lower-roman, and lower-greek.

At the time of writing, not many of the new list-based CSS3 properties and attributes were supported by contemporary web browsers. Otherwise, this article would show (for instance) the fancy new list-style-type attributes. Instead, I show you another more widely supported CSS3 property called text-shadow.

Like the box-shadow defined earlier, the text-shadow property provides a shadow. However, unlike box-shadow, text-shadow actually shadows each individual letter. So for instance, when applying it to list items, you could use the following markup:

li {
  text-shadow: 2px 2px 2px #AA00FF;
}

If, for instance, you have an unordered list with an (X)HTML ID of nav as a navigation bar, you could build something a bit like this:

ul#nav li:hover {
  text-shadow: 2px 2px 2px #AA00FF;
}

This would only provide a text-shadow when you pass your mouse over a list element within the #nav unordered list.

In the past, developers of the CSS3 standard thought that it would be wise to distinguish among an unclicked link, a visited link, an active link, and a link being hovered over. In (X)HTML, these are all the same tag—namely, the <a> tag—but with different browser states. Thankfully, many designers ignore these distinctions, and it has become common to serve styles to a generic link and a hovered-over link.

One near-essential task is to apply a certain style to a generic link (and, therefore, set it, regardless of whether it's unclicked, visited, active, or whatever). Listing 2 provides an example of such an application.

Listing 2. CSS example of link decoration
a, a:link, a:active, a:visited {
  color: #000000;
  text-decoration: none;
  font-weight: bold;
  background-color: #EEEEEE;
}
a:hover {
  text-decoration: underline;
  background-color: #FFFFAA;
}

This markup sets a generic link to color the font black, undo the default underline, make it bold, and set the background color to off-white. In the hover state, it re-applies the underline and establishes a new background color to highlighter yellow. When you test this markup in your browser, you'll notice the background changing from light gray to yellow when you hover over the link and from yellow to light grey when you hover away. You could apply a text shadow to the a:hover, as seen earlier.

When the developers were conceptualising CSS3, they left out any specific <a> tag-related styles, focusing more on generics. Therefore, this article doesn't show you something called transform:rotate, which you could use for <li> tags in navigation (for instance). Instead, combining a few things that you've seen in this article already, you can make something a little like Listing 3.

Listing 3. CSS example of navigation enhanced with some CSS3 properties
a, a:link, a:active, a:visited {
  color: #000000;
  text-decoration: none;
  font-weight: bold;
  background-color: #EEEEEE;
}
li {
  text-align: center;
  list-style-type: none;
  width: 50px;
  padding: 10px;
  margin: 10px;
  background-color:#EEEEEE;
  border: 1px solid #000000;
  -webkit-border-radius: 10px;
  -moz-border-radius: 10px;
  border-radius: 10px;
  -moz-transform:rotate(-20deg);
  -webkit-transform:rotate(-20deg);
  transform:rotate(-20deg);
}
li:hover {
  text-decoration: underline;
  background-color: #FFFFAA;
}

Making columns without tables

Generally speaking, tables are bad as a layout technique, because when you lay out your web pages with tables, you mess with the logical flow of data. Remember at the start of the article I stated that CSS is a layer over the top of (X)HTML, and (X)HTML is actually the data presented in a coherent fashion? Well, the best way to design is to present your data as (X)HTML without any design or style whatsoever: If it looks coherent, you can then apply a CSS style sheet. If you really must edit the (X)HTML to get a certain design to work, make sure you disable CSS to see if it is still coherent.

This is important for two reasons. The first reason is to make it accessible to those who have special visual needs (as they will often have their own default style sheet settings or software). The second is so that machines can read your website. Search engines and other software need to be able to read and follow your website's code so that it can be indexed.

The question, then, is how do you make columns without tables? Simple; you use two <div> boxes, as shown in Listing 4.

Listing 4. (X)HTML example for column divs
<div id="left" class="equal-column">
</div>
<div id="right" class="equal-column">
</div>
<div class="something-below">
</div>

You can then set various design properties within CSS. Listing 5 provides an example.

Listing 5. CSS example for making div columns
div.equal-column {
  width: 45%;
  height:100%:
}
div#left {
 float: left;
}
div#right {
 float: right;
}
div.something-below {
 width: 100%;
 clear: both;
}

This markup sets both columns to a 45% width, then makes the left one stick to the left and the right one stick to the right. Finally, you have another <div> with class something-below, which you want to go across the screen below both columns. This is a useful technique for quickly and easily getting two columns on a screen.

In CSS3, there is yet another ingenious idea, which is textual columns. In other words, a paragraph automatically splits into two if the column-count property is set to a number:

div#textual-columns {
  -webkit-column-count: 2;
  -moz-column-count: 2;
  column-count: 2;
}

This markup sets a <div> with ID textual-columns to have two textual columns. However, you may notice that it equalises the height of each column, which may seem a bit unexpected in comparison to columns that you would find in a newspaper or magazine.


Font typography

Three generic font families were defined by CSS2.1: serif, sans-serif, and monospace. These fonts will always work on every system—they won't necessarily look exactly the same, but, in general, they should be at least a backup font if the primary fonts fail. So, for example, in your body CSS declaration, you could use something like this:

body {
  font-family: Univers, sans-serif;
}

Where you have chosen the Univers font and the sans-serif default if Univers is not available on the user's computer.

CSS3 has enhanced this function slightly by introducing the @font-face element, which is quite a complicated mechanism for transmitting a font across the web specifically for your website. It can be quite useful if you want a fancy font, but it is an advanced topic best left for the typographic experts. However, this font face-style development has been made simpler by third-party providers such as Google Font API and Typekit in the form of font downloading.

Font downloading

Google Font API and Typekit provide their own systems for downloading fancy fonts across systems. How this works is a mixture of (X)HTML, JavaScript, and CSS3, and so will probably only work on the more modern browsers.

For now, let's focus on the Google Font API, which is free and easy to access. To get this function to work, first add a line to your (X)HTML head area indicating that you want to use the Architects Daughter font in the Google Font Directory:

<link href='http://fonts.googleapis.com/css?family=Architects+Daughter' 
        rel='stylesheet' type='text/css'>

Then, simply apply the style using CSS:

body {
  font-family: 'Architects Daughter', serif;
}

Your site is now using the Architects Daughter Google Font. My recommendation, however, is not to use a "too-fancy" font for the whole site. Make sure your site continues to be clean, coherent, and crisp.


Conclusion

CSS2.1 and CSS3 are big enough topics to be covered in a book. This article has scratched the surface of writing good-quality style sheets, and from here, you can take your knowledge with you when looking up the CSS reference material elsewhere on the World Wide Web.

By using (X)HTML and CSS independently and unobtrusively from each other, you can maximise the potential for standards compatibility, accessibility, and search engine optimisation. CSS is a good technology, as are XHTML and HTML, but it must be used in a standardised fashion. These standards can be the building material for web design, but they are not the design itself, and good design is something that must be practiced and perfected.

Resources

Learn

Get products and technologies

Discuss

Comments

developerWorks: Sign in

Required fields are indicated with an asterisk (*).


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Information in your profile (your name, country/region, and company name) is displayed to the public and will accompany any content you post, unless you opt to hide your company name. You may update your IBM account at any time.

All information submitted is secure.

Choose your display name



The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


All information submitted is secure.

Dig deeper into Web development on developerWorks


static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Web development
ArticleID=657459
ArticleTitle=Get started with CSS
publish-date=05102011