The CSS Anthology: 101 Essential Tips, Tricks and Hacks 1

Share this article

Cascading Style Sheets sound intimidating. The name alone conjures up images of cryptic code and syntax too difficult for the layperson to grasp. In reality, however, CSS is one of the simplest and most convenient tools available to Web developers.

This article is actually a chapter from the SitePoint Book The CSS Anthology: 101 Essential Tips, Tricks & Hacks.

Who Should Read This Book?

This book is aimed at people who need to work with CSS – Web designers and developers who have seen the cool CSS designs out there, but don’t have the time to wade through masses of theory and debate in order to create a site. Each problem is solved with a working solution that can be implemented as-is or used as a starting point.

This book isn’t a tutorial; while Chapter 1, Getting Started with CSS covers the very basics of CSS, and the early chapters cover simpler techniques than those that follow, you will find the examples easier to grasp if you have a basic grounding in CSS.

What’s Covered In This Series?

This series of chapters will comprise the first four chapters from The CSS Anthology: 101 Essential Tips, Tricks & Hacks.

Chapter 1: Getting Started with CSS

This chapter does not follow the same format as the rest of the book – it’s simply a quick CSS tutorial for anyone who needs to brush up on the basics of CSS. If you’ve been using CSS in your own projects, you might want to skip this chapter and refer back to it on a needs basis, if you find you want to look into basic concepts in more detail.

Chapter 2: Text Styling and Other Basics

This chapter covers techniques for styling and formatting text in your documents; font sizing, colors, and the removal of annoying extra white space around page elements are explained as the chapter progresses. Even if you’re already using CSS for text styling, you will find some useful tips here.

Chapter 3: CSS and Images

Combining CSS and images can create powerful visual effects. This chapter looks at the ways in which you can do this, and covers background images (not just on the body), and positioning text with images, among other topics.

Chapter 4: Navigation

We all need navigation, and this chapter explains how to do it, CSS-style. The questions of CSS replacements for image-based navigation, CSS “tab” navigation, combining background images with CSS text to create attractive and accessible menus, and using lists to structure navigation in an accessible way are addressed in this chapter.

For information, see the book’s page.

But now, let’s get started with CSS!

In this first chapter, which takes a different format than the rest of the book, I’ll guide you through the basics of CSS and show you how it can be used to simplify the task of managing a consistently formatted Website. If you’ve used CSS to format text on your sites, you may want to skip this chapter and jump straight to the solutions that begin in Chapter 2, Text Styling and Other Basics. And, if you’d rather read this information offline, you can download the .pdf version of the first 4 chapters here.

The Problem with HTML

CSS is a language that’s used to define the formatting applied to a Website, including colors, background images, typefaces (fonts), margins, and indentation. If you’ve never used CSS before, you could be forgiven for thinking, “Well, I do all that now with HTML tags. Why would I need CSS?” It’s a valid question that’s best answered with an illustration of the problems that can arise when we define styles using HTML.

At present, a popular design choice is to use a sans-serif font (such as Arial, Verdana, Tahoma, etc.) for the main body text of a site. Since most Web browsers default to a serif font like Times New Roman, creating a complex Web page layout using a sans-serif font will often involve a lot of <font> tags. In a complex layout, you might see ten or twenty <font> tags dedicated to applying the same font to all text on a page. Multiply this by five – the number of pages on a modest site – and we’re in the neighborhood of one hundred tags. A beefier site might have fifty pages or more, in which case you’re looking at one thousand <font> tags, all of them dedicated to applying that one basic, consistent style to your document’s text.

Now here’s the kicker: your client calls you late one Friday afternoon to say, “Verdana is nice, but everyone uses it. Let’s use Tahoma instead.” Fancy search-and-replace tools aside, you’re now faced with the task of adjusting one hundred, one thousand, or even more <font> tags to make what, from your client’s perspective, seems like a very simple change. You can kiss that ski weekend you had planned goodbye. And, try not to groan aloud – it doesn’t go over well with most customers.

If you know your HTML, you may be thinking that the <basefont> tag, which lets you set the default font to be used throughout a page, provides a nice solution to this problem. But even then, you’d have to adjust one tag for each page of your site. Add another font style to the equation (if, say, you wanted to use a different font for that fancy navigation bar of yours), and the problem returns in full.

Another reason why you shouldn’t use HTML to format your site is that these presentational elements are deprecated (flagged to be removed in future specifications) and can’t be used if you wish to follow a Strict DOCTYPE such as HTML 4.01 Strict or XHTML 1.0 Strict. While your page will still be valid if you use a transitional DOCTYPE, it’s good practice to avoid using these deprecated elements where possible. As you’ll discover through the examples in this book, CSS allows you to do lots of things that you can’t do with HTML alone, so there are many reasons why you should use CSS – but let’s stop talking and see some CSS in action!

Defining Styles with CSS

The basic purpose of CSS is to allow the designer to define a style (a list of formatting details such as fonts, sizes, and colors) and then, to apply it to one or more portions of one or more HTML pages using a selector. Let’s look at a basic example to see how this is done.

Consider the following HTML document outline:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"  
   "https://www.w3.org/TR/xhtml1/DTD/xhtml1-  
    transitional.dtd">  
<html xmlns="https://www.w3.org/1999/xhtml">  
<head>  
<title>A Simple Page</title>  
<meta http-equiv="content-type"  
   content="text/html; charset=iso-8859-1" />  
</head>  
<body>  
<h1><font face="sans-serif" color="#3366CC">First  
Title</font>  
</h1>  
<p>...</p>  
 
<h2><font face="sans-serif" color="#3366CC">Second  
Title</font>  
</h2>  
<p>...</p>  
 
<h2><font face="sans-serif" color="#3366CC">Third  
Title</font>  
</h2>  
<p>...</p>  
</body>  
</html>

This document contains three headings, created using <h1> and <h2> tags. To make these headings stand out more, I used <font> tags to display them in a light blue, sans-serif font (Windows browsers will display them in Arial, for example). Notice the repetition involved, even at this basic level. I had to specify the details of the font I wanted three separate times. Wouldn’t it make sense to define the font just once, then apply it to my headings? Here’s the CSS version:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"  
   "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
<html xmlns="https://www.w3.org/1999/xhtml">  
<head>  
<title>A Simple Page</title>  
<meta http-equiv="content-type"  
   content="text/html; charset=iso-8859-1" />  
<style type="text/css">  
h1, h2 {  
font-family: sans-serif;  
color: #3366CC;  
}  
</style>
 
</head>  
<body>  
<h1>First Title</h1>  
<p>...</p>  
 
<h2>Second Title</h2>  
<p>...</p>  
 
<h2>Third Title</h2>  
<p>...</p>  
</body>  
</html>

All the magic lies between the <style> tags in the <head> of the document, where we define our light blue, sans-serif font and apply it to all <h1> and <h2> tags in the document. Don’t worry about the syntax; I’ll explain it in detail in a moment. Meanwhile, the <font> tags have completely disappeared from the <body>, leaving our document looking a lot less cluttered. Changes to the style definition at the top of the page will affect all three headings, as well as any other headings that are added to the page.

Now that you have an idea of what CSS does, let me explain the different ways of using CSS styles in your HTML documents. The simplest way of putting CSS styles into your Web pages is to use the <style> tag, as I did in the example above. This lets you declare any number of CSS styles by placing them inside the <style> tag, as follows:

<style type="text/css">  
CSS Styles here  
</style>

The type attribute specifies the language that you’re using to define your styles. CSS is the only language in wide use as of this writing, and is indicated with the value text/css.

While it’s nice and simple, the <style> tag has one major disadvantage. Specifically, if you want to use a particular set of styles throughout your site, you’ll have to repeat those style definitions in a <style> tag at the top of every one of your site’s pages.

A more sensible alternative is to put those definitions in a plain text file (usually given a .css filename), then link your documents to that file. Any changes to the style definitions in that one file will affect all the pages that link to it. This achieves the objective of site-wide style definitions mentioned earlier.

To link a document to a CSS text file (say, styles.css), place a <link> tag in the document’s header:

<link rel="stylesheet" type="text/css" href="styles.css" />

Let’s return to the original example in which three headings shared a single style; that document would now look like this:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"  
   "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
<html xmlns="https://www.w3.org/1999/xhtml">  
<head>  
<title>A Simple Page</title>  
<meta http-equiv="content-type"  
   content="text/html; charset=iso-8859-1" />  
<link rel="stylesheet" type="text/css" href="styles.css" />  
</head>  
<body>  
<h1>First Title</h1>  
<p>...</p>  
 
<h2>Second Title</h2>  
<p>...</p>  
 
<h2>Third Title</h2>  
<p>...</p>  
</body>  
</html>

The styles.css file would contain the style definition:

h1, h2 {  
 font-family: sans-serif;  
 color: #3366CC;  
}

As with an image file, you can reuse this styles.css file across as many pages as you need. Not only will it save you typing, it also ensures a consistent look to the headings across your entire site.

CSS Selectors

Every CSS style definition has two components: the selector, which defines the tags to which the style will be applied, and the properties, which specify what the style actually does. In the previous example, the selector was h1, h2, specifying that the style should apply to all <h1> and <h2> tags. The remainder of the style definition comprised the attributes, specifying the font and color that should be applied by the style. In this section, I’ll describe the basic CSS selector types and give examples of each.

Tag Selectors

The most basic form of selector is that which we have already seen. By naming a particular HTML tag, you can apply a style definition to every occurrence of that tag in the document. This is often used to set the basic styles that will appear throughout a Website. For example, the following might be used to set the default font for a Website:

body, p, td, th, div, blockquote, dl, ul, ol {   
 font-family: Tahoma, Verdana, Arial, Helvetica, sans-serif;  
 font-size: 1em;  
 color: #000000;  
}

This rather long selector is a list of tags, all of which will take on the style definition (font, size, and color). In theory, the <body> tag is all that’s needed (as all the other tags appear inside the <body> tag, and would thus inherit its properties), but many browsers don’t properly carry style properties into tables and other elements. Thus, I specified the other elements for the sake of completeness.

Pseudo-Class Selectors

The formatting of the <a> tag in HTML is more versatile than is the formatting of most other tags. By specifying link, vlink, and alink attributes in the <body> tag, you can set the colors for the various states of the links in your page (unvisited, visited, and being clicked on, respectively). CSS provides its own way of doing this, and adds a fourth state that’s applied when the mouse hovers over the link. Consider the following example:

a:link { color: #0000FF; }   
a:visited { color: #FF00FF; }  
a:hover { color: #00CCFF; }  
a:active { color: #FF0000; }

This code contains four CSS style definitions. Each of the selectors uses what is termed a pseudo-class of the <a> tag. The first, link, applies to unvisited links only, and specifies that they should be blue. The second, visited, applies to visited links, and makes them magenta. The third style definition, hover, overrides the first two by making links light blue when the mouse is moved over them, whether they’ve been visited or not. The final style definition makes links red when they’re clicked on. Because active appears last, it overrides the first three, so it will take effect whether the links have been visited or not, and whether the mouse is over them or not.

Class Selectors

Assigning styles to tags is all well and good, but what happens if you want to assign different styles to identical tags occurring in different places within your document? This is where CSS classes come in. Consider the following style, which makes all paragraph text in the page blue:

p { color: #0000FF; }

Now, what if you had a sidebar on your page with a blue background? You wouldn’t want text in the sidebar to be blue as well, because it would be invisible! What you need to do is define a class for your sidebar text, then assign a CSS style to that class:

p { color: #0000FF; }   
.sidebar { color: #FFFFFF; }

This second rule uses a class selector that indicates that the style should be applied to any tag of the sidebar class. The period indicates that a class is being named, instead of a tag. To create a paragraph of text of the sidebar class, you add a class attribute to the tag:

<p class="sidebar">This text will be white, as specified by the   
 CSS style definitions above.</p>

Now, what if there were links in your sidebar? By default, they’d be rendered just like any other links in your page; however, add a class="sidebar" attribute to the tag, and they’ll turn white, too:

<p class="sidebar">This text will be white, <a class="sidebar"   
     href="link.html">and so will this link</a>.</p>

That’s pretty neat, but what if you wanted to make the links stand out a bit more by displaying them in bold text? Adding the bold text attribute to the sidebar class will make your whole sidebar bold. You need a CSS selector that selects links of the sidebar class only. By combining a tag selector with a class selector, you can do exactly that:

p { color: #0000FF; }   
.sidebar { color: #FFFFFF; }  
a.sidebar:link, a.sidebar:visited { font-weight: bold; }

Note that we’ve also used the :link and :visited pseudo-classes to specify <a> tags that are links (as opposed to <a name="..."> tags that are not).

Note also that our sidebar links are still white – both of the styles pertaining to the sidebar class apply to our sidebar links. If we specified a different color in the third style, however, links would adopt that new color, because the third selector is more specific, and CSS styles are applied in order of increasing selector specificity.

Incidentally, the process of applying multiple styles to a single page element is called, and is where Cascading Style Sheets got their name.

Contextual Selectors

If your sidebar happens to contain a lot of links, it becomes tedious to assign the sidebar class to every single <a> tag. Wouldn’t it be nice to use a selector to select any link that appeared inside a paragraph of the sidebar class? That’s what contextual selectors are for: selecting a tag based on its context, that is, based on the tag(s) that contain it.

Here’s the new CSS:

p { color: #0000FF; }   
.sidebar { color: #FFFFFF; }  
p.sidebar a:link, p.sidebar a:visited {  
 font-weight: bold;  
 color: #FFFFFF;  
}

And here’s the updated HTML:

<p class="sidebar">This text will be white,   
 <a href="link.html">and so will this link</a>.</p>

As you can see, a contextual selector provides a list of selectors separated by spaces that must match tags “from the outside in.” In this case, since the link (matched by the a:link or a:visited selector) occurs inside a sidebar paragraph (matched by the p.sidebar selector), the style applies to the link.

Note that, to keep the link white, we had to add that color to the CSS attributes for the links, as the style for the sidebar class no longer applies to the links.

ID Selectors

Similar to class selectors, ID selectors are used to select one particular tag, rather than a group of tags. The tag that you select is identified by an ID attribute as follows:

<p id="sidebar1">This paragraph is uniquely identified by the ID   
 "sidebar1".</p>

An ID selector is simply the ID preceded by a hash (#). Thus, the following style will make the above paragraph white:

#sidebar1 { color: #FFFFFF; }

ID selectors can be used in combination with the other selector types. The following style, for example, applies to unvisited links appearing in the sidebar1 paragraph:

#sidebar1 a:link {   
 font-weight: bold;  
 color: #FFFFFF;  
}

Other selector types exist, but they’re not widely used. Support for them in some browsers (especially Netscape 4) is buggy at best.

CSS Properties

In the examples used so far in this chapter, we’ve used several common CSS properties like color, font-family, font-size, and font-weight. In the rest of the book, we’ll be using these properties – and a lot more.

Summary

This chapter has given you a taste of CSS and its usage at the most basic level. If you haven’t used CSS before, but have a basic understanding of the concepts discussed in this chapter, you should be able to start using the examples in this book. The examples in the early chapters of this book are somewhat simpler than those found near the end, so, if you haven’t worked with this technology before, you might want to begin with the earlier chapters. These will build on the knowledge you gained in this chapter to get you using and, I hope, enjoying CSS.

Watch out for the next chapter of The CSS Anthology: 101 Essential Tips, Tricks & Hacks — it’ll be on SitePoint soon. Or, if you can’t wait, download the fist 4 chapters free now.

Rachel AndrewRachel Andrew
View Author

Rachel Andrew is a front and back-end web developer, author and speaker. Her books include the recent Get Ready for CSS Grid Layout and she is a regular contributor to a number of publications both on and offline. Rachel is co-founder of the CMS Perch, a Google Developer Expert and an Invited Expert to the CSS Working Group. She writes about business and technology on her own site at rachelandrew.co.uk.

Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week