Cascading Stylesheets (CSS)

What is CSS?

CSS stands for Cascading Style Sheets. It has the power to apply a set of default rules to an HTML page. These rules affect the page's presentation as well as the normal behavior of tags shown. With CSS, your pages can share the same layout and have the flexibility to render properly in several different types of media (screen, tv, printer, etc).


Syntax

You should be familiar with the syntax of HTML tags and attributes by now. The CSS syntax is similar to that. Here's what HTML's syntax looks like:

<tag attribute="value">Content</tag>

And here's what CSS looks like.

selection { property: value }

Selections can be a tag, a class, an ID, or a combination of them using inheritance. These will be explained later in the tutorial. Property works similar to how attributes work in an HTML tag. And value works the same way in both. So basically, we have the element on the left, followed by curly brackets. Inside, we have a property, a colon, and the value. CSS uses a colon (:) instead of an equal sign (=). To add more than one property to the same selection, separate the properties with a semicolon (;).

selection { property: value; property: value}

As with HTML, whitespace is respected. The only exception is that each statement must be on it's own line. Other than that, you can organize your CSS as you like such as follows:

selection
	{
	property:value;
	property:value
	}
selection
	{
	property:value;
	property:value
	}
selection{property:value;property:value}


How to specify CSS

There are four ways to specify CSS in your page. They are listed below ranked by their priority of influence.

  1. Inline styles
  2. Internal stylesheet
  3. External stylesheet
  4. Browser settings
Inline styles

To specify CSS inline, you use the style attribute on the tag you're applying the CSS to. This is the most direct way to influence the tag's behavior.

<p style="color:red">Red text</p>;

Inline styles do not use selections or curly brackets because they only apply the values to the tag they're used on.

Internal stylesheet

An internal stylesheet is a block of CSS statements inside <style> tags (<style> goes inside <head>). The style tag requires the type attribute with a value of "text/css".

<head>
	<style type="text/css">
	body{background-color:gray}
	</style>
</head>

The entire syntax is used for internal stylesheets because you can specify CSS that applies to the entire page.

External stylesheets

External stylesheets work the same way as internal stylesheets except they are located inside their own file. The external file contains CSS statements (it does not contain <style> tags). Here's how you link the HTML page to the external sheet:

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

The required rel attribute must be set to "stylesheet" and the type attribute must be set to "text/css". The href attribute specifies the path to the file to load (works the same way as with the <a> tag).

Browser Settings

Your browser may have default settings that it applies to the page. For example, in most browsers, all links are underlined, unclicked links are blue, and visited links are purple.


Selections: Tag, Class, ID

When specifying CSS through internal or external sheets, it's necessary to use selections in order to control which tags are affected. There are 3 types of elements you can specify as a selection. These are tag, class, and ID.

Tag

To specify a tag, simply put the name of the tag before the curly brackets.

tag{property:value}
Class

Classes let you simplify your CSS by grouping multiple elements into one name. Instead of applying the same inline CSS to a bunch of tags, you can assign a class that can be used over and over. Here's how we create a class:

<style type="text/css">
.yourclass{text-align:center}
</style>
		

To use a class name as a seleector, you put a period (.) in front of it's name in the internal or external stylesheet.

<p class="yourclass">The CSS defined in the internal CSS stylesheet takes affect here</p>
<div class="yourclass">And here</div>
		

The name of your class has to start with a letter. You cannot use whitespace characters or punctuation marks at all in the name.

ID

The id attribute works just like the class attribute. But unlike classes, you cannot use them on more than one tag in the same page. IDs must be unique. The same rules apply to naming the ID as with a class. To specify an ID as a selection, you put a pound symbol in front of the name.

#main{background-color:green}
<div id="main">Text</div>

You've already seen IDs in action in Internal Links. Rather than put a class or inline style, you can reuse the existing ID by specifying it in the stylesheet. You can only use an ID once per page.


Multiple Selections

If you wanted to specify the same effect to different classes, IDs, and tags, you can do it all in one statement.

body, .myClass, #myID{text-align:center}


Inheritance

When you apply style to a tag, that tag's children may inherit the style too.

<p style="color:red">
Red Text. <span>Text color inherited from parent tag</span>
</p>

Unless span had style defined to display a different color of text, it inherits the text color of it's parent. The parent always has the power of intervention above the grandparent. Not every style is inheritable. A list will be made in the future to list all of the different styles.


Cascading

With internal and external stylesheets, not only can you specify what selectionss you want to apply them to, but you can apply them to specific ancestry lines. For example, if you had multiple <p> tags and wanted to have a style apply to only the <p> tags on the page that were children of <div> tags, you could do this:

div p{}

The child tag (the right-most selection) doesn't have to be a direct child of the selection to the left of it. It can be a grand-child. The gap between generations doesn't matter as long as the child tag is a descendant.

Also with CSS, you can build onto existing statements per tag.

div{color:red;font-weight:bold}
div p{color:green}

The first thing the browser does is apply bold red text to all <div> tags on the page. Next, it makes the text of the <p> tags (that are descendents of (<div>) and makes their text green. The second statement overwrote the color style that would have been inherited by <p> and made it green. However, the bold still exists (you'll have bold green text). This is because the bold was inherited while only the color was overwritten. This is how style rules can cascade and build upon existing styles. In the above example, it does not matter what order you put the statements in.

parent child {}
grandparent child {}

Commas can also be used to group different parent-child groups in the CSS statements. Take note the order of operations.

parent child, grandparent child {}


Pseudo-elements

Pseudo-elements give us control over certain behaviors of tags. For example, we can control the color a link will turn when we have the mouse over it, or if it has been visited. To use a pseudo-element with an element, put a colon at the end followed by the name of the pseudo-element.

a:hover {color: green}

This makes all <a> tags turn green when the mouse arrow hovers over them.

a:link {color: blue}

This makes all unclicked links blue

a:visited {background-color: #eee}

This makes all links that have been visited have a slightly gray background color.

a:active {color: red}

:active is when you give the element focus. If you click the element but you don't release the mouse button, the element is active or has focus. An element that has focus will have dotted lines surrounding it in some browsers. When you release the mouse button, the element is no longer active (but it still has focus because it was the last thing clicked).

:link and :visited only apply to links. You can use Hover and Active can be used on other elements to change their style when the mouse moves over them or takes focus in most browsers.


Selectors

As well as using parent and child to diversify which tags you're applying CSS to, there are even more ways to control which tags get which styles. The following requires support for CSS2 or higher. Modern browsers support CSS2. Internet Explorer does not support these features.

Direct Descendant
div > span {color:red}

<span> tags that are direct children (child but not grandchild) of a <div> will have red text.

Previous Sibling
b+u {color:green}
<p>
<b>Bold text<br />
<u>Underlined text (turns green from CSS)
</p>

Using the plus sign (+) between 2 elements means they must be siblings in order for the styles to be applied. In the example, if a <u> tag comes directly after a <b>, then the <u> will receive a background-color of #eee. In order for two tags to qualify as siblings, they must have the same parent tag.

Attribute Match
img [border] {text-align:center}

Use the square brackets [] after an element if you want it to apply only to the elements that have the attribute inside those brackets. In the example, any <img> tag that has a border attribute will be centered. This even applies if the attribute is blank (border="").

img [src="Tails.gif"] {background-color:yellow}

This will select all images that have an src attribute with the value of "Tails.gif." The value inside the square brackets must be in quotes.

Attribute Word Matching
img [alt~="Fox"] {text-align:right}

This will match any image that has "Fox" in it's alt text. "Fox" must not have any other characters before and after it except whitespace. For example, it will match "The Fox" but not "XFox".

Language attribute matching
a [lang |= "en"] {color:aqua}

This works just like word matching except it only matches the first word until a space or hyphen (- is found in the value of the attribute. For the example "en" and "en-" will work. " en", "-en", "en ", "enx", "xen" will not match. This can be used to detect character encodings and languages but it's not really that useful.



Back to HTML Tutorial index
Back to Web Tutorials
Back to Web Development
Home

Valid XHTML 1.1! Valid CSS!