Login




Forget password?
Create new account

CSS Techniques

Contents

Applying Styles

You've already seen how to apply styles to HTML tags, such as paragraphs ( <p> ) , headings ( <h1> ) , or the body of the page ( <body> ) . When you create styles for HTML tags, you don't have to change the HTML code at all. However, there are times when you need to be more specific, such as when you want to create styles for just one paragraph, or just one heading, or for other situations. In these cases, you will need to employ other techniques.

The three main methods for applying styles are as follows:

  1. Tag: Create a style for an HTML tag (this style will apply to all instances of that tag)
  2. ID: Create a style for a tag with a unique id (this method applies the style to only one item on the page, because each id must be unique, and only one item per page can have that id)
  3. Class: Create a style for a tag that has a class (this method can be used to apply the same style to an unlimited number of items on the page, by assigning the same class to the items that you want to receive the style)

The concepts of id and class are probably new to you. I'll explain those shortly.

1. Applying Styles to Tags

I've already given examples of this technique. Here is an example of a style that will apply to all links (e.g. all instances of the <a> tag):

a {
  background-color: blue;
  color: white;
  text-decoration: underline;
  }  

To use this technique, just write the name of the tag, then type the style attributes inside of the curly brackets. Remember to put semi-colons at the end of each style declaration.

2. Applying Styles Using the id Attribute

ID attributes can be assigned to any tag. The example below shows a <p> tag and an <a> tag with id attributes:

<p id="first_paragraph">Here is my paragraph. It has a link to 
<a href="http://www.gmu.edu" id="gmu">George Mason University.</a></p>

The name of the id is completely up to you. It doesn't matter what you call the id. You could call it "horseradish" or "red_balloon_number_5" if you like. Usually it makes sense to choose names that make sense in the context of the page, though. When naming id attributes, you should observe these rules:

In your style sheet, you can create a style for a tag with an id by using the pound sign ( # ) and the name of the id, like this:

#first_paragraph { 
  background-color: white;
  color: black;
  }

#gmu {
  background-color: green;
  color: yellow;
  }

I will re-emphasize that you can have only one id per page with any given name. You can only have one tag with the id of "first_paragraph" and only one tag with the id of "gmu".

Question: If you can only have one item with any given id per page, is the id method very useful at all?

Answer: Actually, yes, it is very useful. Most styles on most web sites can be applied either directly to tags or to items with specific id attributes. This is because you can set the global styles (e.g. for all paragraphs) using styles applied to tags and as far as the rest of the items are concerned, most designs have only one of each item. For example, there is usually only one main menu in a web site design (often a list of links across the top of the page). There is usually only one site logo (often in the upper left hand corner). There is usually only one main content area, one footer (with links to copyright info or contact info), and perhaps one side menu. Given the fact that there is only one of each, it makes sense to use the id technique in these cases.

3. Applying Styles Using the class Attribute

If you need to apply the same style in multiple places throughout a web page, it makes sense to use the class attribute. Here are two paragraphs with a class attribute:

<p class="highlight">This paragraph has a highlight background color.</p> 
<p class="highlight">This paragraph also has a highlight background color.</p> 
<p>This paragraph does NOT have a highlight background color.</p> 

The CSS file uses a period ( . ) to reference items with class attributes, as shown below:

.highlight {
  background-color: yellow;
  }

Question: But what if you want to apply the "highlight" class to only part of a paragraph? How do you do that?

Answer: You would use a generic tag called a <span> element (explained in more detail in the next section), and apply the class to that element, as follows:

<p>This is a paragraph with <span class="highlight">a highlighted phrase</span> inside it.</p> 

Notice that there is an opening <span> element and a closing </span> element. The "highlight" class will be applied to the text in between the opening and closing tags.

Using <div> and <span> Elements

There are a couple of generic HTML tags called <div> and <span> which have no real semantic meaning. They're not paragraphs or headings or list items or table cells or links, or any other meaningful tag like the ones we've talked about up until now. The <div> and <span> tags don't mean anything from a semantic or grammatical point of view. Their primary purpose is to allow web developers to apply styles to areas within the web page that are not easily defined by other kinds of tags.

Note: By the way, if you're wondering what "semantic" means, here's one definition: "Of or relating to meaning, especially meaning in language" (from the American Heritage Dictionary). Headings, paragraphs, list items and all those other things provide meaning to text. The <div> and <span> elements do not.

Sometimes you want to apply a style to the semantic elements (headings, paragraphs, etc), but sometimes it makes more sense to apply styles to a chunk of text that doesn't really fit into a semantic unit. Maybe you want to apply a style to four paragraphs, or to three words. In these cases it sometimes makes sense to use a unit that can successfully group the items, but which doesn't apply any semantic meaning. In the example screenshot below, a border was applied around two paragraphs, but not around the others. The border groups the paragraphs visually.

The HTML code looks like this (with the paragraph text shortened):

<p>Paragraph here, etc., etc.</p>
<div id="border_here">
  <p>Paragraph here, etc. etc.</p>  
  <p>Paragraph here, etc. etc.</p>
</div>
<p>Paragraph here, etc. etc.</p>

The CSS code looks like this:

#border_here {
  border: red solid 5px;
  padding: 1em;
  }

To give another example, you might want to create a visual column of text. A column doesn't really have semantic meaning. Columns are just ways of formatting the text. If you have a two-column article and convert it to one column, you haven't lost any meaning. You've only lost the visual formatting. You can create column-like effects by grouping the text using <div> tags and then applying the appropriate styles.

Block vs. Inline

At this point it would be good to revisit the idea of block level content versus inline content.

The <div> tag is a block level tag. That means that anything within the <div> tag takes up a rectangular "block" of visual space. Without any extra styles, this block of space extends all the way across the browser window. For the sake of illustration, I've created a <div> tag below and applied a background color of purple so that you can see what it looks like.

This text is inside of a <div> tag.

Using styles, I can make this block of text as wide or high as I like. I can change the color, add a border, and do all kinds of fancy things with it. But the main point for now is that a <div> is a rectangle that starts on a new line, meaning that you can't insert a <div> in the middle of a paragraph or any other semantic block level tag.

The <span> tag, on the other hand, is an inline tag. Inline tags can be added in the middle of block level tags. They can even be added in the middle of other inline tags. They don't start on a new line. They don't change the flow of the text. Other inline tags include links, <strong> and <em>.

In this paragraph, I've created a span around these words. Like the <div> example above, the <span> is styled to give the text a purple background. the difference is that the <span> is within the paragraph, and does not cause the text to start on a new line.

Reminder: Neither the <div> nor the <span> which I created give the text any additional meaning. They only change the color of the background. The <div> and <span> elements can be useful under some circumstances to enhance visual appeal. They're not good for conveying extra meaning. A blind person using a screen reader will not know that the background color has changed. In fact, screen readers ignore styles almost completely. (There are a few exceptions to this, but a discussion of those exceptions would take us beyond the scope of this lesson.) If you use styles or colors to try to convey meaning (for example, by saying "all the green words are important"), you are probably going to make the content inaccessible to a person using a screen reader, since they can't see the styles.

Question: Which methods can you use to apply styles to <div> and <span> elements?

Answer: You can use any of the methods already discussed. You can apply a style to all <div> or <span> tags, or you can apply a style to only one <div> or <span> tag using the id attribute, or you can apply a style to multiple tags, including <div> and <span>, using the class attribute. All methods are ok.

Grouping Style Declarations

You can apply style declarations to more than one element:

h1, h2, h3, .side_items, #top_paragraph
  {
  color: red;
  }

In the above example, all of the items specified will have red text. Notice that there are commas between all of the items that will receive the style, and that there is no comma at the end of the list. Also notice that all three methods of applying styles are represented in this example, the first three items are tags, the next item references a class, and the next item references an id. It's ok to mix and match them like this.

In a related idea, you can specify more than one class for any given tag:

<p class="highlight style2 style3">Here is the paragraph, with three classes applied.</p> 

Notice that the class attributes are separated by spaces, not commas. I don't know why they use commas for one technique and spaces for another, but that's just the way it is. Sorry.

You cannot apply multiple id attributes to anything:

WRONG:

<p id="id1 id2 id3">This is wrong.</p> 

But you can apply both a class and an id:

OK:

<p id="id1" class="class1">This is ok.</p> 

Or even an id plus multiple class attributes:

OK:

<p id="id1" class="class1 class2 class3">This is ok.</p> 

If you apply multiple styles to a tag, remember that the last style declared is the one that has precedence in cases where more than one style reference the same property. For example, if all three of the styles above deal with font color, the font color in class3 will be implemented.

Complex Style Declarations

Sometimes you need to be very specific when assigning styles. Here is an example:

#main_content #section1 h1.highlight {
  background-color: orange;
  }

If you read this style in a sort of backwards way, the style (background-color: orange) will apply to the item with a class of highlight (class="highlight"), which is inside of the heading level 1 ( <h1> ), which is inside of an item with an id of section1 (id="section1"), which is inside of an item with an id of main_content (id="main_content").

Note: Notice that there is no space between the h1 and the .highlight, but there are spaces between the references to id attributes. Why? I don't know. Just because. That's the way CSS works.

Here is another example:

p a img.special {
  border: none;
  }

This one says that all images with the class of special (class="special") which happen to be inside of links ( <a> ) inside of paragraphs ( <p> ) will have no border.

And here is another example:

.dark_background strong {
  color: white;
  }

This one says that all <strong> tags which happen to be in items with a class of dark_background (class="dark_background") will have white text.

CSS Colors

In the examples I've shown so far, I've typed out the names of colors, such as black, white, green, red, blue, etc. What if you want a non-standard color, such as "puce" or "dark bluish green" or a "really light gray with a hint of purple"? How do you specify those colors? The answer is that you have to use a hexadecimal code for the color, or use the RGB value. There are hexadecimal and RGB codes even for common colors such as black (hexadecimal code: #000000; RGB value: 0 0 0) or white (hexadecimal code: #ffffff; RGB value: 255 255 255), but hexadecimal codes are most useful for less common hues.

Note: RGB codes consist of the values of Red, Green, and Blue, respectively, on a scale of 0 to 255. Hexadecimal codes are just a bunch of strange combinations of numbers and letters invented by mathematicians with nothing better to do. You can quote me on that.

Dreamweaver can help you find the hexadecimal code for pretty much any color that you need, but not the RGB value, so I'm going to stick to hexadecimal codes here. When you create styles in the code view in Dreamweaver, a box of color options pops up to allow you to choose the color you're looking for. The box pops up as soon as you type the colon when defining color, background-color, or other color-related attributes.

You can then use the "eyedropper" tool to select the color you like. As soon as you select the color, the hexadecimal value of that color appears in the text.

If you click on the "color wheel" icon , you will be given even more color options to choose from.

Units of Measurement and Dimensions

When setting the size of things, there are many options in CSS, including inches, centimeters, pixels, ems, and other units. The most commonly-used are em, %, and px (pixels).

An "em" is defined as "the width of a square or nearly square piece of type, used as a unit of measure for matter set in that size of type" (American Heritage Dictionary, 4th edition). The definition of "em" is in some ways even more confusing than the term itself, but I've also heard it explained as "the size of the letter M in a particular font." I'm not sure if the latter definition is entirely accurate, but the key point to remember is that "ems" are relative to the size of the font, whereas units such as pixels or inches or centimeters are not.

Unit Brief Explanation When to Use
em Relative to font size Use em when you want to be able to enlarge or shrink items as you enlarge or shrink the font.
% Relative to the container Use % when you want items to resize in proportion to the size of the browser window, which means that areas will shrink or grow as you shrink or enlarge your browser window. An item with a width of 50% would be half the width of the browser window. If an item inside the first item also has width set to 50%, the second item will actually be 25% of the total width of the browser window (because it is 50% of the container, which is already at 50%).
 px Relative to the size and resolution of the monitor Don't use px unless you absolutely have to. The trouble with pixel-based measurements is that users may not be able to resize the items in when resizing fonts or their browser window. This can be bad for accessibility. Sometimes it is acceptable use pixels for things like borders, though borders can be set using other units also, such as ems.

NOTE: I did not finish writing all of the content that I wanted to in some of the sections below, but I'm providing links to resources that explain these concepts. I may fill in these sections later when I get the time.

Margin and Padding

Borders

Backgrounds and Background Images

Text, Fonts and Font Families

Lists

Positioning and Layout

Hover Effects and Other "Pseudo-Classes"

Media Types

http://www.w3schools.com/css/css_mediatypes.asp

Accessibility Issues with CSS

Note: This is an important section. Don't skip it.

To learn about accessibility issues with style sheets, read the following WebAIM resources:

The other sections are more "advanced" but also useful.

Common Mistakes to Avoid

As you experiment with styles, make sure you avoid these common mistakes:

Error: Forgetting to link your HTML file to the CSS file

Your styles won't work unless you create a link in your HTML file to the CSS file as explained in the section about external style sheets.

Error: Forgetting to put a semi-colon at the end of the line in a style declaration

If you leave off the semi-colon, the styles won't work properly.

Correct:

p {
	color:red;
	background-color:white;
	}

Incorrect:

p {
	color:red
	background-color:white
	}

Note: Technically speaking, if you leave off the semi-colon on the last style declaration, it won't matter, but if you have more than one style declaration, such as color, margin, padding, and background-color, all of them except the last one must have semi-colons at the end. I usually put semi-colons at the end of every line, just in case I need to add to the list of styles later.

Error: Misspellings

If you type "maggenta" (incorrect) instead of "magenta" (correct), or "margen" (incorrect) instead of "margin" (correct), the styles won't work. All misspellings will cause the style to fail. The word "grey" has two spellings: "gray" and "grey." Both are acceptable.

Error: Improper Syntax

You have to follow the syntax given in the example files. You have to use curly brackets, for example { } not parentheses ( ). You have to remember the colon in-between the style type and the style declaration.

Correct:

background-color: white;

Incorrect (colon missing):

background-color white;

Also incorrect (hypen missing):

background color: white; 

Note: you can write the style declaration with or without a space after the colon. The empty space doesn't matter in this case.

Error: Putting a space between a value and the unit type

Correct:

margin:25em;

Incorrect:

margin: 25 em;

Creative Commons License
This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 2.5 License.